简单易懂for of 与 for in的区别

遍历数组通常使用for循环,ES5的话也可以使用forEach,ES5具有遍历数组功能的还有map、filter、some、every、reduce、reduceRight等,只不过他们的返回结果不一样。但是使用foreach遍历数组的话,使用break不能中断循环,使用return也不能返回到外层函数。

1

2

3

4

5

6

7

8

Array.prototype.method=function(){

  console.log(this.length);

}

var myArray=[1,2,4,5,6,7]

myArray.name="数组"

for (var index in myArray) {

  console.log(myArray[index]);

}

使用for in 也可以遍历数组,但是会存在以下问题:

1.index索引为字符串型数字,不能直接进行几何运算

2.遍历顺序有可能不是按照实际数组的内部顺序

3.使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性

所以for in更适合遍历对象,不要使用for in遍历数组。

那么除了使用for循环,如何更简单的正确的遍历数组达到我们的期望呢(即不遍历method和name),ES6中的for of更胜一筹.

1

2

3

4

5

6

7

8

Array.prototype.method=function(){

  console.log(this.length);

}

var myArray=[1,2,4,5,6,7]

myArray.name="数组";

for (var value of myArray) {

  console.log(value);

}

记住,for in遍历的是数组的索引(即键名),而for of遍历的是数组元素值。

for of遍历的只是数组内的元素,而不包括数组的原型属性method和索引name

遍历对象 通常用for in来遍历对象的键名

1

2

3

4

5

6

7

8

9

10

11

Object.prototype.method=function(){

  console.log(this);

}

var myObject={

  a:1,

  b:2,

  c:3

}

for (var key in myObject) {

  console.log(key);

}

for in 可以遍历到myObject的原型方法method,如果不想遍历原型方法和属性的话,可以在循环内部判断一下,hasOwnPropery方法可以判断某属性是否是该对象的实例属性

1

2

3

4

5

for (var key in myObject) {

  if(myObject.hasOwnProperty(key)){

    console.log(key);

  }

}

    同样可以通过ES5的Object.keys(myObject)获取对象的实例属性组成的数组,不包括原型方法和属性。

1

2

3

4

5

6

7

8

9

Object.prototype.method=function(){

  console.log(this);

}

var myObject={

  a:1,

  b:2,

  c:3

}

Object.keys(myObject).forEach(function(key,index){<br>  console.log(key,myObject[key])<br>})

  参考文章:http://www.infoq.com/cn/articles/es6-in-depth-iterators-and-the-for-of-loop

Arrays(数组)

Arrays(数组)就是类列表(list-like)对象。数组原型上有各种方法,允许对其进行操作,比如修改和遍历等操作。下面手在一个数组上进行的 for...of 操作:

// array-example.js
const iterable = ['mini', 'mani', 'mo'];
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// mini
// mani
// mo

其结果就是打印出 iterable 数组中的每一个值。

Demo: jsbin.com/dimahag/edi…

Maps(映射)

Map 对象就是保存 key-value(键值) 对。对象和原始值可以用作 key(键)或 value(值)。Map 对象根据其插入方式迭代元素。换句话说, for...of 循环将为每次迭代返回一个 key-value(键值) 数组。

// map-example.js
const iterable = new Map([['one', 1], ['two', 2]]);
 
for (const [key, value] of iterable) {
  console.log(`Key: ${key} and Value: ${value}`);
}
 
// Output:
// Key: one and Value: 1
// Key: two and Value: 2

Demo: jsbin.com/lofewiw/edi…

Set(集合)

Set(集合) 对象允许你存储任何类型的唯一值,这些值可以是原始值或对象。 Set(集合) 对象只是值的集合。 Set(集合) 元素的迭代基于其插入顺序。 Set(集合) 中的值只能发生一次。如果您创建一个具有多个相同元素的 Set(集合) ,那么它仍然被认为是单个元素。

// set-example.js
const iterable = new Set([1, 1, 2, 2, 1]);
 
for (const value of iterable) {
  console.log(value);
}
// Output:
// 1
// 2

尽管我们的 Set(集合) 有多个 1 和 2 ,但输出的只有 1 和 2 。

Demo: jsbin.com/fajozob/edi…

String(字符串)

字符串用于以文本形式存储数据。

// string-example.js
const iterable = 'javascript';
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// "j"
// "a"
// "v"
// "a"
// "s"
// "c"
// "r"
// "i"
// "p"
// "t"

这里,对字符串执行迭代,并打印出每个索引上的字符。

Demo: jsbin.com/rixakeg/edi…

Arguments Object(参数对象)

把一个参数对象看作是一个类数组(array-like)对象,并且对应于传递给函数的参数。这是一个用例:

// arguments-example.js
function args() {
  for (const arg of arguments) {
    console.log(arg);
  }
}
 
args('a', 'b', 'c');
// Output:
// a
// b
// c

你可能会想,发生了什么事?! 如前所述,当调用函数时,arguments 会接收传入 args() 函数的任何参数。所以,如果我们传递 20 个参数给 args() 函数,我们将打印出 20 个参数。

Demo: jsbin.com/ciqabov/edi…

Generators(生成器)

生成器是一个函数,它可以退出函数,稍后重新进入函数。

// generator-example.js
function* generator(){ 
  yield 1; 
  yield 2; 
  yield 3; 
}; 
 
for (const g of generator()) { 
  console.log(g); 
}
 
// Output:
// 1
// 2
// 3

function* 定义了一个生成器函数,该函数返回生成器对象(Generator object)。更多关于生成器相关的信息,可以点击这里

Demo: jsbin.com/faviyi/edit…

退出迭代

JavaScript 提供了四种已知的终止循环执行的方法:breakcontinuereturn 和 throw。让我们来看一个例子:

const iterable = ['mini', 'mani', 'mo'];
 
for (const value of iterable) {
  console.log(value);
  break;
}
 
// Output:
// mini

在这个例子中,我们使用 break 关键字在一次执行后终止循环,所以只有 mini 被打印出来。

Demo: jsbin.com/tisuken/edi…

普通对象不可迭代

for...of 循环仅适用于迭代。 而普通对象不可迭代。 我们来看一下:

const obj = { fname: 'foo', lname: 'bar' };
 
for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function
    console.log(value);
}

在这里,我们定义了一个普通对象 obj ,并且当我们尝试 for...of 对其进行操作时,会报错:TypeError: obj[Symbol.iterator] is not a function

Demo: jsbin.com/sotidu/edit…

我们可以通过将类数组(array-like)对象转换为数组来绕过它。该对象将具有一个 length 属性,其元素必须可以被索引。我们来看一个例子:

// object-example.js
const obj = { length: 3, 0: 'foo', 1: 'bar', 2: 'baz' };
 
const array = Array.from(obj);
for (const value of array) { 
    console.log(value);
}
// Output:
// foo
// bar
// baz

Array.from() 方法可以让我通过类数组(array-like)或可迭代对象来创建一个新的 Array(数组) 实例。

Demo: jsbin.com/miwofin/edi…

For…of vs For…in

for...in 循环将遍历对象的所有可枚举属性。

//for-in-example.js
Array.prototype.newArr = () => {};
Array.prototype.anotherNewArr = () => {};
const array = ['foo', 'bar', 'baz'];
 
for (const value in array) { 
  console.log(value);
}
// Outcome:
// 0
// 1
// 2
// newArr
// anotherNewArr

for...in 不仅枚举上面的数组声明,它还从构造函数的原型中查找继承的非枚举属性,在这个例子中,newArr 和 anotherNewArr 也会打印出来。

Demo: jsbin.com/quxojof/edi…

for...of 更多用于特定于集合(如数组和对象),但不包括所有对象。

注意:任何具有 Symbol.iterator 属性的元素都是可迭代的。

Array.prototype.newArr = () => {};
const array = ['foo', 'bar', 'baz'];
 
for (const value of array) { 
  console.log(value);
}
// Outcome:
// foo
// bar
// baz

for...in 不考虑构造函数原型的不可枚举属性。它只需要查找可枚举属性并将其打印出来。

猜你喜欢

转载自blog.csdn.net/qq_37818095/article/details/81774920