我有一个数组如下:

levelinfoarray["test"] = new Array(16,20,4,5,"Test level");
levelinfoarray[1] = new Array(29,25,17,13,"Introduction");
levelinfoarray[2] = new Array(16,24,6,4,"Counting...");
levelinfoarray[3] = new Array(16,20,4,5,"Where am I going?");
...

我想遍历数组并获得这样的级别编号和级别描述
Test) Test level
1) Introduction
2) Counting...
3) Where am I going?
...

我已经尝试过for循环和forEach,但是两者都只给了我编号的条目。我将如何获得“测试”条目?

最佳答案

当数组具有非数字键时,它实际上是一个对象。使用for...in

for (key in levelinfoarray) {
    if (levelinfoarray.hasOwnProperty(key)) {
        console.log(key+') '+levelinfoarray[key][4]);
    }
}

附言不要使用new Array,请使用数组文字:
levelinfoarray["test"] = [16,20,4,5,"Test level"];

10-06 05:56