Javascript:如何调用字符串的数组索引

Javascript : How do I call the array index of the string?

本文关键字:字符串 数组 索引 调用 何调用 Javascript      更新时间:2023-09-26

您好,当您更改字符串以在javascript中调用数组时,我遇到了问题,请帮助我,

我有一个数组:

var fruit=['Apple','Banana','Orange'];

我有来自 mysql 的数据字符串:

示例:var string = '0,2';

如何显示与var string对应的fruit数组?

(感谢您的帮助)

您必须split()字符串才能获得索引数组而不是索引字符串:

var indexes = '0,2'.split(','); //use the ',' char to split the string

现在,您必须选择与之前创建的新索引数组中的每个索引对应的水果值。

var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
  res.push(fruit[index]); //Add the juicy fruit :)
});

你得到了新的阵列(res)与多汁的水果:)

JSFiddle

编辑:

或者,更短/更好的解决方案(感谢 Xotic750)(映射函数的第二个参数指定上下文 (this))

var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
    return this[index];
}, fruits);
我不知道

它是否有效,但这是我能想到的:

var x = [];
for (var i = 0; i>=string.length; i+=2) {
 x.push(fruit[string[i]]);
}

但仅使用偶数,因为字符串中也存在逗号。

您需要

使用 Split() 方法将string拆分为数组:

var myArray = string.split(",");

然后,您可以遍历数组并将其值用作fruit数组中的索引。例如,第一个水果将是:

fruit[myArray[0]];