(for ... in)和(for ... of)语句之间有什么区别? [英] What is the difference between ( for... in ) and ( for... of ) statements?

查看:145
本文介绍了(for ... in)和(for ... of)语句之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道什么是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循环感到困惑.

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆