当有编号的数组时,引用数组中第一个元素的正确语法是什么?
someArray1["someString", "anotherString"];
someArray2["someString", "anotherString"];
someArray3["someString", "anotherString"];
heresANumber = 1;
grabAString(heresANumber);
function grabAString(theNumber){
var string = 'someArray' + theNumber[0].slice(0,1);
}
是否有一种简单的方法指向顺序编号的数组?
答案 0 :(得分:0)
您可以对订购的商品进行数组处理。
function grabAString(theNumber){
return array[theNumber - 1];
}
var someArray1 = ["someString", "anotherString"],
someArray2 = ["someString", "anotherString"],
someArray3 = ["someString", "anotherString"],
array = [someArray1, someArray2, someArray3],
heresANumber = 1;
console.log(grabAString(heresANumber));
高级版本采用一个从零开始的索引,例如
0, ..., n - 1
并通过索引直接访问。
另一种解决方案是将short hand properties放在变量名称为属性的对象中。这样可以使用组合键进行访问。
function grabAString(theNumber){
return object['someArray' + theNumber];
}
var someArray1 = ["someString", "anotherString"],
someArray2 = ["someString", "anotherString"],
someArray3 = ["someString", "anotherString"],
object = { someArray1, someArray2, someArray3 },
heresANumber = 1;
console.log(grabAString(heresANumber));
答案 1 :(得分:0)
将这些数组分配为对象的属性,以便可以对动态属性名称使用[]
表示法
const arrs = {
someArray1 : ["someString", "anotherString"],
someArray2 : ["someString", "anotherString"],
someArray3 : ["someString", "anotherString"]
}
heresANumber = 1;
function grabAString(theNumber) {
return arrs['someArray' + theNumber][0];
}
console.log( grabAString(heresANumber))