gpt4 book ai didi

javascript - 无法将数组作为数组进行操作

转载 作者:行者123 更新时间:2023-11-28 16:56:40 25 4
gpt4 key购买 nike

我正在创建一个像这样的数组

var p1_s1 = {
'title': 'p1_s1', 'titleDisplayed': 'p1_s1', 'type': 'numbers', 'page':1,'strings': 1, 'length': 7, 'placeholder':'0000000', 'painted':'black', 'notPainted':'#ffe485', 'left':410, 'top':161, 'width':394, 'height':144,
'ids':[
['path5472','path5440','path5488','path5520','path5504','path5456','path5536'],
['path5360','path5328','path5376','path5408','path5392','path5344','path5424'],
['path5584','path5552','path5600','path5632','path5616','path5568','path5648'],
['path4912','path4880','path4928','path4960','path4944','path4896','path4976'],
['path5024','path4992','path5040','path5072','path5056','path5008','path5088'],
['path5136','path5104','path5152','path5184','path5168','path5120','path5200'],
['path5248','path5216','path5264','path5296','path5280','path5232','path5312']
]
};

然后,在脚本代码中我调用这个变量

...
var ids = p1_s1['ids'];
for(var i = ids.length;i>=0;i--)
{
drawOneNumber( ids[i], parseInt(value[i]) );
}
...
function drawOneNumber( place, number )
{
number = numberToSegments( number );
console.log(place);
for(var i=0;i<number.length;i++)
{
console.log( place[i] );
}
...
}

在字符串 console.log(place); 上,我在控制台中看到了它应该是的数组。

(7) […]
​0: "path5248"
​1: "path5216"
​2: "path5264"
​3: "path5296"
​4: "path5280"
​5: "path5232"
​6: "path5312"
​length: 7

但是在字符串 console.log( place[i] ); 上我收到错误

TypeError: place is undefined

同样的情况

place.forEach(element => console.log(element));

Code Array.isArray(place); 返回 true,但我无法像数组一样操作此变量。我究竟做错了什么?谢谢。

最佳答案

问题出在for循环

你定义了如果数组的长度为 5,则最后一个元素将在第 4 个位置访问。

当您定义i = ids.length并尝试访问ids[i]时,它将是未定义的,并且变量place位于你的drawOneNumber函数也将是未定义的。

示例:

const arr = ["foo", "bar", "youhou"];

console.log(arr.length);
console.log(arr[arr.length]);

尝试:for(var i = ids.length -1 ;i>=0;i--)

关于javascript - 无法将数组作为数组进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957985/

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