当我写一些这样的
javascript:
@H_404_2@var words = ['word1','word2','word3']
for (word in words) {
console.log(word)
}
所得到的输出是相应词的数字索引.我在Google上做了一些搜索,我找不到这个行为的确切原因.我猜这是完全预期的行为,但我想知道为什么.
谢谢!
解决方法
为什么没有人提供正确答案?你不要使用for / in循环来迭代数组 – 这仅用于迭代普通对象及其键,而不是迭代数组中的项.
你为这个循环迭代数组:
@H_404_2@var words = ['word1','word3']; for (var i = 0,len = words.length; i < len; i++) { // here words[i] is the array element }或者,在现代浏览器中,可以使用数组的.forEach()方法:
@H_404_2@var words = ['word1','word3']; words.forEach(function(value,index,array) { // here value is the array element being iterated });有关更多信息,请参阅here at MDN .forEach().
ndp对this post的引用显示了使用数组可以出错的事情的一些很好的例子.你可以使它有时工作,但并不是写入Javascript数组迭代的聪明的方式.