Javascript:如何调用字符串的数组索引
Javascript : How do I call the array index of the string?
您好,当您更改字符串以在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]];
相关文章:
- 将JSON转换为typescript中的字符串数组
- 在Javascript中将一个值和字符串数组转换为if语句
- 如何将正则表达式包含到字符串数组中
- JavaScript:将字符串数组转换为文本区域
- Knockout中的字符串数组
- 拆分字符串数组(JavaScript)后未定义
- 使用Javascript获取两个字符串之间的字符串数组
- 打印从Spring MVC Controller发送的字符串数组只显示“;toJSON”;在javascript中
- 将一个字符串数组解析为一个新的数组javascript
- AngularJS - 从字符串数组中连续更改文本
- 使用字符串数组中的字符填充 HTML 表
- 如何在 Javascript 中将字符串数组列表插入到表行中
- 创建二维字符串数组
- 如何从字符串数组中获取子字符串数组
- 如何将字符串数组转换为简单数组
- 按字母顺序、数字顺序和特殊字符对字符串数组进行排序
- 如何从字符串数组中获得8个随机唯一元素
- json_encode($myVar);正在给出地图,我想要一个字符串数组
- 函数,返回javascript中两个字符串数组的差值
- Javascript字符串数组转换为用逗号分隔的多个字符串