如何获取数组内部的数组名称?

我正在尝试访问循环中其他数组内的数组名称,但我失败了。如果 fx 不在另一个数组内,我可以访问该数组的名称。Object.keys({thisObject})[0] 但是当它在另一个数组中时它不起作用。


我已经尝试过每个循环,for 循环。在新数组中嵌套初始化数组:


var arr1 = [1,2,3]

var arr2 = [4,5,6]

var arr3 = new Array(arr1,arr2)

尽管如此,在循环中我无法获得 arr1 和 arr2 的名称。我有可能访问它们的值,但不能访问名称..


var cars = new Array("Porshe","Mercedes");

var bikes = new Array("Yamaha","Mitsubishi");


var vehicles = new Array(cars, bikes);



for (var key in vehicles) {

    var value = vehicles[key];// This is retruning whole array, not the name

    console.log(Object.keys({vehicles[key]})[0]) // That does not work

    vehicles[key].forEach(car => {

        console.log(car)


    });

}



//or


for (let i=0;i<vehicles.length;i++){

    console.log(vehicles[i]); //This is also returning whole array - same method.

    for(let j = 0; j< vehicles[i].car.length;j++){

             console.log(vehicles[i][j]);

    }


}

我想要得到的结果是在表格中列出汽车,其中汽车是标题,下面是保时捷、三菱,然后是自行车。


神不在的星期二
浏览 235回答 4
4回答

月关宝盒

const map = new Map();const cars = new Array("Porshe","Mercedes");const bikes = new Array("Yamaha","Mitsubishi");map.set('cars', cars);&nbsp;map.set('bikes', bikes);&nbsp;您可以像这样检索它们:for(let arrayName of map.keys()) {&nbsp; &nbsp; console.log(arrayName);&nbsp; &nbsp; for(let item of map.get(arrayName)) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(item);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}输出:carsPorsheMercedesbikesYamahaMitsubishi

撒科打诨

for (let i=0;i<vehicles.length;i++){&nbsp; &nbsp; &nbsp;for(let j = 0; j< vehicles[i].length;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.log(vehicles[i][j]);&nbsp;&nbsp; &nbsp; &nbsp;}&nbsp;&nbsp;}变量名没有用,当您尝试访问数据时......只有对象存储在数组中,而不是每个变量名。

白板的微信

这是行不通的,另一个数组中的数组不是属性,因此没有 propertyName。你想要做的是创建一个像这样的对象:arr1 = [value1, value2];arr2 = [value1, value2];obj = { 'a1': arr1, 'a2': arr2}然后你可以迭代对象键,因为现在它是一个对象:Object.keys(obj).forEach(key => console.log(key + ' = '+ obj[key]);

万千封印

干得好。var vehicles={cars: ["Porshe","Mercedes"], bikes: ["Yamaha","Mitsubishi"]};for( var vehicle in vehicles){ console.log(vehicle)} // this returns the keys in object i.e. "cars" and "bikes" not the values of arrayfor( var mark in vehicle){ console.log(mark) // this will loop on "bikes" and "cars"要获得您需要做的值。for(var type in vehicles) { // will give type of vehicle i.e. "cars" and "bikes"&nbsp; &nbsp; vehicles[type].forEach(vehicle => { // will get values for each type and loop over them&nbsp; &nbsp; &nbsp; &nbsp; console.log(vehicle); // this will print the values for every car and bike&nbsp; &nbsp; )};}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript