( for... in ) 和 ( for... of ) 语句之间有什么区别? [英] What is the difference between ( for... in ) and ( for... of ) statements?
问题描述
我知道什么是 for... in
循环(它遍历键),但我第一次听说 for... of
(它遍历值).
I know what is a for... in
loop (it iterates over the keys), but I have heard about for... of
for the first time (it iterates over values).
我对 for... of
循环感到困惑.
I am confused about for... of
loop.
var arr = [3, 5, 7];
arr.foo = "hello";
for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (var i of arr) {
console.log(i); // logs "3", "5", "7"
// it doesn't log "3", "5", "7", "hello"
}
我知道 for... of
迭代属性值.那么为什么它不记录 3"、5"、7"、hello"
而不是 3"、5"、?7"
?
I understand that for... of
iterates over property values. Then why doesn't it log "3", "5", "7", "hello"
instead of "3", "5", "7"
?
与 for... in
循环不同,它遍历每个键(0"、1"、2"、foo"
) 并且还迭代 foo
键,for... of
不会迭代 foo
的值> 属性,即 hello"
.为什么会这样?
Unlike for... in
loop, which iterates over each key ("0", "1", "2", "foo"
) and also iterates over the foo
key, the for... of
does not iterate over the value of foo
property, i.e., "hello"
. Why it is like that?
在这里我控制台 for... of
循环.它应该记录 3"、5"、7"、hello"
但它记录 3"、5"、7"代码>.为什么?
Here I console for... of
loop. It should log "3", "5", "7","hello"
but it logs "3", "5", "7"
. Why?
推荐答案
for in
循环遍历对象的可枚举属性名称.
for in
loops over enumerable property names of an object.
for of
(ES6 中的新功能)确实使用了 特定于对象的迭代器 并遍历由此生成的值.
for of
(new in ES6) does use an object-specific iterator and loops over the values generated by that.
在您的示例中,数组迭代器 确实产生数组中的所有值(忽略非索引属性).
In your example, the array iterator does yield all the values in the array (ignoring non-index properties).
这篇关于( for... in ) 和 ( for... of ) 语句之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!