gpt4 book ai didi

javascript遍历数组

转载 作者:行者123 更新时间:2023-11-29 17:10:10 25 4
gpt4 key购买 nike

我有一个数组如下:

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"];

关于javascript遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22108337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com