gpt4 book ai didi

javascript - 无法访问 Javascript 数组中的 FOR...IN

转载 作者:行者123 更新时间:2023-11-30 08:16:07 25 4
gpt4 key购买 nike

我想使用 FOR...IN 以数组形式访问 [] JSON 文字中的对象。但是遍历 FOR...IN 会得到对象 x undefined。请看下面的代码。

var myJSONObject = [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
];

for (var x in myJSONObject) {
alert(x['method']);
}

您可以在此处在线测试代码@ JSBin

问候,
穆尼姆

最佳答案

您不应该使用 for … in 遍历数组:

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

以这种方式循环你的数组:

for (var i = 0, length = myJSONObject.length; i < length; i++) {
alert(myJSONObject[i].method);
}

参见 JSBin .

关于javascript - 无法访问 Javascript 数组中的 FOR...IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3778851/

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