for ... in循环,字符串数组输出索引 [英] for ... in loop with string array outputs indices
问题描述
当我写一些像这样的javascript:
When I write some javascript such as this:
var words = ['word1', 'word2', 'word3']
for (word in words) {
console.log(word)
}
结果输出是相应单词的数字索引。我在Google上进行了一些搜索,但我找不到这种行为的确切原因。我猜这是完全预期的行为,但我想知道原因。
The resulting output is the numeric indices of the respective word. I did some searching on Google and I couldn't find the exact reason for this behavior. I'm guessing that this is completely expected behavior but I would like to know the reason why.
谢谢!
推荐答案
为什么没有人提供正确答案?你永远不会用 for / in
循环迭代数组 - 这只是为了迭代普通对象及其键,而不是迭代数组中的项。
Why is nobody providing the correct answer? You NEVER iterate arrays with a for/in
loop - that is only for iterating plain objects and their keys, not for iterating the items in an array.
你为这样的for循环迭代数组:
You iterate arrays for a for loop like this:
var words = ['word1', 'word2', 'word3'];
for (var i = 0, len = words.length; i < len; i++) {
// here words[i] is the array element
}
或者,在现代浏览器中,您可以使用 .forEach()
数组方法:
Or, in a modern browser, you can use the .forEach()
method of arrays:
var words = ['word1', 'word2', 'word3'];
words.forEach(function(value, index, array) {
// here value is the array element being iterated
});
参见此处在MDN 获取有关 .forEach()
的更多信息。
See here at MDN for more info on .forEach()
.
ndp对这篇文章的引用显示了一些使用数组使用 for / in
可能出错的好例子。你可以使它有时工作,但它不是编写Javascript数组迭代的聪明方法。
ndp's reference to this post shows some good examples of things that can go wrong using for/in
with arrays. You can make it works sometimes, but it is not the smart way to write Javascript array iteration.
或者更多现代,您可以使用ES6 for / of
构造,它是专为迭代迭代而构建的(数组是可迭代的):
Or, in more modern times, you can use the ES6 for/of
construct which is specially built for iterating an iterable (an array is an iterable):
var words = ['word1', 'word2', 'word3'];
for (const w of words) {
console.log(w);
}
或者,如果你想要价值和指数,你可以这样做:
Or, if you want both the value and the index, you can do this:
var words = ['word1', 'word2', 'word3'];
for (const [index, w] of words.entries()) {
console.log(index, ": ", w);
}
有几个优点
over .forEach()
。首先,你有更多的循环控制,因为你可以使用 break
,继续
,返回
控制 .forEach()
没有给你的循环流。此外,回调函数没有额外的开销,因此在某些环境中,它可以更快。
There are several advantages of for/of
over .forEach()
. To start with, you have more loop control as you can use break
, continue
, return
to control the loop flow which .forEach()
does not give you. In addition, there's no additional overhead for a callback function so, in some environments, it can be faster.
这篇关于for ... in循环,字符串数组输出索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!