javascript - for ... in 循环与字符串数组输出索引

标签 javascript

当我写一些像这样的 javascript 时:

var words = ['word1', 'word2', 'word3']

for (word in words) {
    console.log(word)
}

结果输出是相应单词的数字索引。我在谷歌上做了一些搜索,但找不到这种行为的确切原因。我猜这完全是预期的行为,但我想知道原因。

谢谢!

最佳答案

为什么没有人提供正确答案?您永远不要使用 for/in 循环来迭代数组 - 这仅用于迭代普通对象及其键,而不用于迭代数组中的项目。

你像这样为 for 循环迭代数组:

var words = ['word1', 'word2', 'word3'];

for (var i = 0, len = words.length; i < len; i++) {
    // here words[i] is the array element
}

或者你可以使用数组的.forEach()方法:

var words = ['word1', 'word2', 'word3'];

words.forEach(function(value, index, array) {
    // here value is the array element being iterated
});

参见 here at MDN有关 .forEach() 的更多信息。

ndp 对 this post 的引用展示了一些很好的例子,说明在数组中使用 for/in 可能会出错。有时你可以让它工作,但这不是编写 Javascript 数组迭代的聪明方法。


或者,在更现代的时代,您可以使用 ES6 for/of 构造,它是专门为迭代可迭代对象构建的(数组是可迭代对象):

var words = ['word1', 'word2', 'word3'];

for (const w of words) {
    console.log(w);
}

或者,如果您同时需要值和索引,您可以这样做:

var words = ['word1', 'word2', 'word3'];

for (const [index, w] of words.entries()) {
    console.log(index, ": ", w);
}

.forEach() 相比,for/of 有几个优点。首先,您有更多的循环控制,因为您可以使用 breakcontinuereturn 来控制 .forEach 的循环流程() 不给你。此外,回调函数没有额外的开销,因此在某些环境中,它可以更快。

关于javascript - for ... in 循环与字符串数组输出索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480020/

相关文章:

php - 数据库数组到预期的 javascript 格式

javascript - 如何使用 jquery 启用/禁用 div 层

javascript - jquery 扩展返回 $.each 混淆

javascript - 当鼠标不在 HTML 元素上时,将 Rythm.js 播放的音乐静音

javascript - AngularJS 种子 : putting JavaScript into separate files (app. js、controllers.js、directives.js、filters.js、services.js)

javascript - jQuery.data 不再适用于窗口?

javascript - Buffer + writeUInt32LE 从 NodeJS 到 Javascript

javascript - 检查单选按钮的值

javascript - Reactjs - 如何将值从子组件传递到祖父组件?

javascript - 在 PHP 包含的 header 上更改 CSS