for...in和for...of

341 阅读1分钟

20190305102532665.png

1.for…of循环可以代替数组实例的forEach方法

const arr = ['red', 'green', 'blue'];

arr.forEach((item,index)=> {
  console.log(item); // red green blue
  console.log(index);   // 0 1 2
});

2.JavaScript 原有的for…in循环,只能获得对象的键名,不能直接获取键值。ES6 提供for…of循环,允许遍历获得键值

var arr = ['a', 'b', 'c', 'd'];

for (let i in arr) {
  console.log(i); // 0 1 2 3
}

for (let i of arr) {
  console.log(i); // a b c d
}

3.for…of循环调用遍历器接口,数组的遍历器接口只返回具有数字索引的属性。

let arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
  console.log(i); // "0", "1", "2", "foo"
}

for (let i of arr) {
  console.log(i); //  "3", "5", "7"
}

4.for…of循环会正确识别 32 位 UTF-16 字符。

for (let x of 'a\uD83D\uDC0A') {
  console.log(x);
}
// 'a'
// '\uD83D\uDC0A'

区别

for…in循环的缺点(for in循环对象)- for in总是得到对像的key或数组,字符串的下标
  1. 数组的键名是数字,但是for…in循环是以字符串作为键名“0”、“1”、“2”等等。
  2. for…in循环不仅遍历数字键名,还会遍历手动添加的其他键,甚至包括原型链上的键。
  3. 某些情况下,for…in循环会以任意顺序遍历键名。 总之,for…in循环主要是为遍历对象而设计的,不适用于遍历数组。
for…of函数的优点 (for of循环数组)- for of和forEach一样,是直接得到值
  1. 有着同for…in一样的简洁语法,但是没有for…in那些缺点。
  2. 不同于forEach方法,它可以与break、continue和return配合使用。
  3. 提供了遍历所有数据结构的统一操作接口。