码迷,mamicode.com
首页 > 其他好文 > 详细

ES6: for...of VS for...in

时间:2017-09-12 13:52:55      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:其他   关键字   arguments   字符   console   erro   not   使用   script   

for...of和for...in是js中常用的两个遍历的方法,但是它们遍历是有区别的,最主要的区别就是:

(1)for...of是遍历key, value中的value即键值,for...of一般是forEach的替代方法。

    for...in是遍历key, value中的key即键名,而key一般就是索引index的作用,所以记忆的话in可以对应index,for...in是遍历index的,这样可以很容易区分出for..of和for..in。

(2)for...of循环可以使用的范围包括数组、Set和Map结构、某些类似数组的对象(比如arguments对象、DOM NodeList对象)、Generator对象,以及字符串

(3)for...of是ES6提供的方法,for...in是js原生的方法

(4) for..of不能遍历普通对象而for..in能遍历普通对象

var es6 = {
edition: 6,
committee: "TC39",
standard: "ECMA-262"
};
for (e in es6) {
console.log(e);
}
// edition
// committee
// standard
for (e of es6) {
console.log(e);
}
// TypeError: es6 is not iterable

(5)for...in和for...of遍历过程中可以用break,return,其他的遍历方法不能用这两个关键字

var es6 = {
edition: 6,
committee: "TC39",
standard: "ECMA-262"
};

for (e in es6) { 
    if(e == ‘committee‘) {
         break;
    } else {
        console.log(e);
    }
}   

//edition

var arr1 = [1,2,3,4];

for(value of arr1){
    if(value == 3) {
         break;
    }else{ 
        console.log(value)
    }
}

// 1
// 2

(6)for...in循环有几个缺点

  • 数组的键名是数字,但是for...in循环是以字符串作为键名“0”、“1”、“2”等等。
  • for...in循环不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键。
  • 某些情况下,for...in循环会以任意顺序遍历键名。

总之,for...in循环主要是为遍历对象而设计的,不适用于遍历数组。

(7)for...of的优点

  • 有着同for...in一样的简洁语法,但是没有for...in那些缺点。
  • 不同用于forEach方法,它可以与break、continue和return配合使用。
  • 提供了遍历所有数据结构的统一操作接口。

 

ES6: for...of VS for...in

标签:其他   关键字   arguments   字符   console   erro   not   使用   script   

原文地址:http://www.cnblogs.com/ycherry/p/7509533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!