es6语法中forEach和for的区别

2025年03月06日 建站教程

forEach是ES5提出的,挂载在可迭代对象原型上的方法,for循环是js提出时就有的循环方法。哪些二则有什么区别呢?下面web建站小编给大家科普一下!

forEach是一个迭代器

let arr = [1, 2, 3, 4];
arr.forEach(function (self, index, arr) {
  console.log(`当前元素为${self}索引为${index},属于数组${arr}`);
}, person)

for循环可以控制循环起点

let arr = [1, 2, 1],
  i = 0,
  length = arr.length;

for (; i < length; i++) { 
// 删除数组中所有的1 
  if (arr[i] === 1) { 
    arr.splice(i, 1); 
    //重置i,否则i会跳一位 
    i--; 
  }; 
}; 
console.log(arr); // [2] 
//等价于 
var arr1 = arr.filter(index => index !== 1);
console.log(arr1) // [2]

forEach 是一个迭代器,他与 for 循环本质上的区别是 forEach 是负责遍历(Array Set Map)可迭代对象的,而 for 循环是一种循环机制,只是能通过它遍历出数组。

本文链接:http://so.lmcjl.com/news/24403/

展开阅读全文
相关内容