- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用 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/
我是一名优秀的程序员,十分优秀!