es6新增循环怎么使用

发布时间:2022-11-08 09:41:23 作者:iii
来源:亿速云 阅读:167

ES6新增循环怎么使用

ES6(ECMAScript 2015)引入了许多新的语法和功能,其中包括一些新的循环方式。这些新的循环方式不仅使代码更加简洁易读,还提供了更多的灵活性和功能。本文将详细介绍ES6中新增的循环方式,并通过示例代码展示如何使用它们。

1. for...of 循环

for...of 循环是ES6中引入的一种新的循环方式,用于遍历可迭代对象(如数组、字符串、Map、Set等)。与传统的 for 循环和 for...in 循环相比,for...of 循环更加简洁和直观。

1.1 基本用法

const arr = [1, 2, 3, 4, 5];

for (const item of arr) {
  console.log(item);
}

在上面的代码中,for...of 循环遍历数组 arr,并将每个元素赋值给变量 item,然后在循环体中打印出来。

1.2 遍历字符串

for...of 循环也可以用于遍历字符串中的每个字符:

const str = "hello";

for (const char of str) {
  console.log(char);
}

1.3 遍历Map和Set

for...of 循环还可以用于遍历 MapSet

const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);

for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}

const set = new Set([1, 2, 3, 4, 5]);

for (const item of set) {
  console.log(item);
}

1.4 遍历自定义可迭代对象

for...of 循环还可以用于遍历自定义的可迭代对象。要实现一个可迭代对象,需要在对象上实现 Symbol.iterator 方法:

const myIterable = {
  [Symbol.iterator]: function* () {
    yield 1;
    yield 2;
    yield 3;
  }
};

for (const item of myIterable) {
  console.log(item);
}

2. for...in 循环

for...in 循环在ES6之前就已经存在,但它主要用于遍历对象的属性。在ES6中,for...in 循环的行为没有发生变化,但它仍然是一个重要的循环方式。

2.1 基本用法

const obj = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

for (const key in obj) {
  console.log(`${key}: ${obj[key]}`);
}

在上面的代码中,for...in 循环遍历对象 obj 的所有可枚举属性,并将每个属性名赋值给变量 key,然后在循环体中打印出属性名和对应的值。

2.2 遍历数组

虽然 for...in 循环可以用于遍历数组,但它并不推荐用于数组遍历,因为它会遍历数组的所有可枚举属性,包括原型链上的属性:

const arr = [1, 2, 3];
arr.foo = 'bar';

for (const index in arr) {
  console.log(index);
}

在上面的代码中,for...in 循环不仅会遍历数组的索引,还会遍历 foo 属性。

2.3 遍历对象原型链

for...in 循环会遍历对象原型链上的所有可枚举属性。如果不希望遍历原型链上的属性,可以使用 hasOwnProperty 方法进行过滤:

const obj = Object.create({
  protoProp: 'protoValue'
});

obj.ownProp = 'ownValue';

for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(`${key}: ${obj[key]}`);
  }
}

3. Array.prototype.forEach 方法

Array.prototype.forEach 方法在ES6之前就已经存在,但它仍然是一个常用的数组遍历方法。forEach 方法接受一个回调函数作为参数,并为数组中的每个元素调用该回调函数。

3.1 基本用法

const arr = [1, 2, 3, 4, 5];

arr.forEach((item, index) => {
  console.log(`arr[${index}] = ${item}`);
});

在上面的代码中,forEach 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受两个参数:当前元素和当前索引。

3.2 中断 forEach 循环

forEach 方法的一个缺点是它无法通过 breakreturn 语句中断循环。如果需要中断循环,可以使用 for...of 循环或 Array.prototype.some 方法。

const arr = [1, 2, 3, 4, 5];

arr.some((item) => {
  console.log(item);
  if (item === 3) {
    return true; // 中断循环
  }
});

4. Array.prototype.map 方法

Array.prototype.map 方法在ES6之前就已经存在,但它仍然是一个常用的数组遍历方法。map 方法接受一个回调函数作为参数,并为数组中的每个元素调用该回调函数,最后返回一个新数组。

4.1 基本用法

const arr = [1, 2, 3, 4, 5];

const newArr = arr.map((item) => {
  return item * 2;
});

console.log(newArr); // [2, 4, 6, 8, 10]

在上面的代码中,map 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。map 方法返回一个新数组,新数组中的每个元素都是回调函数的返回值。

4.2 使用箭头函数

由于 map 方法的回调函数通常比较简单,可以使用箭头函数来简化代码:

const arr = [1, 2, 3, 4, 5];

const newArr = arr.map(item => item * 2);

console.log(newArr); // [2, 4, 6, 8, 10]

5. Array.prototype.filter 方法

Array.prototype.filter 方法在ES6之前就已经存在,但它仍然是一个常用的数组遍历方法。filter 方法接受一个回调函数作为参数,并为数组中的每个元素调用该回调函数,最后返回一个新数组,新数组中的元素是原数组中满足回调函数条件的元素。

5.1 基本用法

const arr = [1, 2, 3, 4, 5];

const newArr = arr.filter((item) => {
  return item % 2 === 0;
});

console.log(newArr); // [2, 4]

在上面的代码中,filter 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。filter 方法返回一个新数组,新数组中的元素是原数组中满足回调函数条件的元素。

5.2 使用箭头函数

由于 filter 方法的回调函数通常比较简单,可以使用箭头函数来简化代码:

const arr = [1, 2, 3, 4, 5];

const newArr = arr.filter(item => item % 2 === 0);

console.log(newArr); // [2, 4]

6. Array.prototype.reduce 方法

Array.prototype.reduce 方法在ES6之前就已经存在,但它仍然是一个常用的数组遍历方法。reduce 方法接受一个回调函数和一个初始值作为参数,并为数组中的每个元素调用该回调函数,最后返回一个累加值。

6.1 基本用法

const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // 15

在上面的代码中,reduce 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受两个参数:累加值和当前元素。reduce 方法返回一个累加值,累加值的初始值为 0

6.2 使用箭头函数

由于 reduce 方法的回调函数通常比较简单,可以使用箭头函数来简化代码:

const arr = [1, 2, 3, 4, 5];

const sum = arr.reduce((acc, cur) => acc + cur, 0);

console.log(sum); // 15

7. Array.prototype.findArray.prototype.findIndex 方法

Array.prototype.findArray.prototype.findIndex 方法是ES6中新增的数组遍历方法。find 方法用于查找数组中满足条件的第一个元素,findIndex 方法用于查找数组中满足条件的第一个元素的索引。

7.1 find 方法

const arr = [1, 2, 3, 4, 5];

const found = arr.find((item) => {
  return item > 3;
});

console.log(found); // 4

在上面的代码中,find 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。find 方法返回数组中满足条件的第一个元素。

7.2 findIndex 方法

const arr = [1, 2, 3, 4, 5];

const foundIndex = arr.findIndex((item) => {
  return item > 3;
});

console.log(foundIndex); // 3

在上面的代码中,findIndex 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。findIndex 方法返回数组中满足条件的第一个元素的索引。

8. Array.prototype.everyArray.prototype.some 方法

Array.prototype.everyArray.prototype.some 方法是ES6中新增的数组遍历方法。every 方法用于检查数组中的所有元素是否都满足条件,some 方法用于检查数组中是否至少有一个元素满足条件。

8.1 every 方法

const arr = [1, 2, 3, 4, 5];

const allGreaterThanZero = arr.every((item) => {
  return item > 0;
});

console.log(allGreaterThanZero); // true

在上面的代码中,every 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。every 方法返回一个布尔值,表示数组中的所有元素是否都满足条件。

8.2 some 方法

const arr = [1, 2, 3, 4, 5];

const someGreaterThanThree = arr.some((item) => {
  return item > 3;
});

console.log(someGreaterThanThree); // true

在上面的代码中,some 方法遍历数组 arr,并为每个元素调用回调函数。回调函数接受一个参数:当前元素。some 方法返回一个布尔值,表示数组中是否至少有一个元素满足条件。

9. Array.prototype.flatArray.prototype.flatMap 方法

Array.prototype.flatArray.prototype.flatMap 方法是ES6中新增的数组遍历方法。flat 方法用于将嵌套数组扁平化,flatMap 方法用于先对数组中的每个元素执行映射操作,然后将结果扁平化。

9.1 flat 方法

const arr = [1, [2, [3, [4]]]];

const flattened = arr.flat(2);

console.log(flattened); // [1, 2, 3, [4]]

在上面的代码中,flat 方法将数组 arr 扁平化,扁平化的深度为 2

9.2 flatMap 方法

const arr = [1, 2, 3];

const flattened = arr.flatMap((item) => {
  return [item, item * 2];
});

console.log(flattened); // [1, 2, 2, 4, 3, 6]

在上面的代码中,flatMap 方法先对数组 arr 中的每个元素执行映射操作,然后将结果扁平化。

10. Array.prototype.keysArray.prototype.valuesArray.prototype.entries 方法

Array.prototype.keysArray.prototype.valuesArray.prototype.entries 方法是ES6中新增的数组遍历方法。keys 方法返回数组的索引迭代器,values 方法返回数组的元素迭代器,entries 方法返回数组的索引和元素迭代器。

10.1 keys 方法

const arr = ['a', 'b', 'c'];

for (const key of arr.keys()) {
  console.log(key);
}

在上面的代码中,keys 方法返回数组 arr 的索引迭代器,for...of 循环遍历索引迭代器并打印出每个索引。

10.2 values 方法

const arr = ['a', 'b', 'c'];

for (const value of arr.values()) {
  console.log(value);
}

在上面的代码中,values 方法返回数组 arr 的元素迭代器,for...of 循环遍历元素迭代器并打印出每个元素。

10.3 entries 方法

const arr = ['a', 'b', 'c'];

for (const [index, value] of arr.entries()) {
  console.log(`${index}: ${value}`);
}

在上面的代码中,entries 方法返回数组 arr 的索引和元素迭代器,for...of 循环遍历索引和元素迭代器并打印出每个索引和元素。

11. Object.keysObject.valuesObject.entries 方法

Object.keysObject.valuesObject.entries 方法是ES6中新增的对象遍历方法。Object.keys 方法返回对象的属性名数组,Object.values 方法返回对象的属性值数组,Object.entries 方法返回对象的属性名和属性值数组。

11.1 Object.keys 方法

const obj = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

const keys = Object.keys(obj);

console.log(keys); // ['name', 'age', 'city']

在上面的代码中,Object.keys 方法返回对象 obj 的属性名数组。

11.2 Object.values 方法

const obj = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

const values = Object.values(obj);

console.log(values); // ['Alice', 25, 'New York']

在上面的代码中,Object.values 方法返回对象 obj 的属性值数组。

11.3 Object.entries 方法

const obj = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

const entries = Object.entries(obj);

console.log(entries); // [['name', 'Alice'], ['age', 25], ['city', 'New York']]

在上面的代码中,Object.entries 方法返回对象 obj 的属性名和属性值数组。

12. SetMap 的遍历方法

SetMap 是ES6中新增的数据结构,它们也提供了遍历方法。

12.1 Set 的遍历方法

Set 是一个不包含重复值的集合,它提供了 forEach 方法用于遍历集合中的每个元素。

const set = new Set([1, 2, 3, 4, 5]);

set.forEach((value) => {
  console.log(value);
});

在上面的代码中,SetforEach 方法遍历集合 set 中的每个元素,并打印出每个元素。

12.2 Map 的遍历方法

Map 是一个键值对的集合,它提供了 forEach 方法用于遍历集合中的每个键值对。

const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);

map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

在上面的代码中,MapforEach 方法遍历集合 map 中的每个键值对,并打印出每个键和值。

13. 总结

ES6引入了许多新的循环方式,包括 for...of 循环、Array.prototype.forEachArray.prototype.mapArray.prototype.filterArray.prototype.reduceArray.prototype.findArray.prototype.findIndexArray.prototype.everyArray.prototype.someArray.prototype.flatArray.prototype.flatMapArray.prototype.keysArray.prototype.valuesArray.prototype.entriesObject.keysObject.valuesObject.entries 等方法。这些新的循环方式不仅使代码更加简洁易读,还提供了更多的灵活性和功能。在实际开发中,可以根据具体需求选择合适的循环方式。

推荐阅读:
  1. ES6新增的数组知识是什么
  2. ES6如何新增math,Number方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

es6

上一篇:jquery如何判断一个元素是否是另一个元素的子元素

下一篇:vue动态绑定多个class官方实例语法无效如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》