我有多个带有动态名称(编号)的数组,我需要从每个数组中获取第一个值。
代码看起来像这样
var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];
for (var cols=1; cols <=5; cols++) {
var imgs = array.cols[0];
}
我在控制台中收到“((索引):131 Uncaught ReferenceError:未定义数组)”
答案 0 :(得分:4)
我了解到您想获得每个数组的"1","1","1"
首个值。
map()
map()
内部,返回数组的第一个元素。
var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];
let arrays = [array1,array2,array3];
let res = arrays.map(([a]) => a);
console.log(res);
答案 1 :(得分:1)
如果您的数组在全局范围内,也许您可以使用window
对象访问它们:
var array1 = ["1","2","3"];
var array2 = ["1","2","3"];
var array3 = ["1","2","3"];
for (let i = 1; i <= 3; i++)
{
console.log(window["array" + i][0]);
}
另一个更通用的替代方法是将数组保存在另一个结构中,例如Map
或Array
。我将展示如何使用Map做到这一点:
let array1 = ["1","2","3"];
let array2 = ["1","2","3"];
let array3 = ["1","2","3"];
let myMap = new Map([["1", array1], ["2", array2], ["3", array3]]);
myMap.forEach(([first, ...rest]) => console.log(first));