forEach in JavaScript

forEach in JavaScript

本文关键字:JavaScript in forEach      更新时间:2023-09-26

有人可以向我深入解释forEach如何在JavaScript中工作,它做什么以及如何使用它吗?我所知道的是,它是一种使用函数和数组的循环。我理解其他循环,如forwhiledo-whilefor-in,但我就是无法理解forEach循环。我已经尝试了其他在线资源,但我仍然很迷茫,不知道它的作用以及如何正确"创建"一个,因为我不明白语法。一些帮助将不胜感激。谢谢

> Array.prototype.forEach 是一个函数,它遍历数组中的所有项目,执行第一个参数中定义的回调函数。语法如下所示:

Array.forEach(function(currentValue, index, array) {}, thisArg);
函数

内部是执行什么代码,回调函数的参数如下: currentValue, currentIndex, arrayThatWasCalledOn

它通常用于循环遍历长数组。第二个参数是thisArgument,此参数设置为的任何值都是函数作用域内相应的 this 关键字。

Array.forEach(function() {console.log(this.name);}, {name: "value"});

请注意,一旦循环启动,break语句就不能用于退出循环。这就是建议使用 for 循环的原因。

下面是一个代码示例:

var fruits = ["lemon", "apple", "orange", "lettuce"];
fruits.forEach(function(currentFruit) {
  if (isFruit(currentFruit) === false) {
    console.log("Error: Item is not a fruit!");
  }
}

理解forEach方法的最佳方法是从头开始创建它。forEach 原生 Javascript 函数基本上是一个内部有一个循环的函数,它将使用迭代器函数(回调)对集合中的每个项目(集合可以是数组或对象)执行。

前任:

  var forEach = function(collection, iterator) {    
    if (Array.isArray(collection)) {
      for (var i = 0; i < collection.length; i++) {
        iterator(collection[i], i, collection);
      }
    } else {
      for (var key in collection) {
        iterator(collection[key], key, collection);
      }
    } 
  };

现在,如果您调用传递集合和迭代器的 forEach 函数,它应该记录集合中的每个名称:

  // This is your collection
  var names = ['John', 'Robert', 'James'];
  // This is the action that you want to perform on each item
  var action = function(item) {
    console.log(item);
  }
  // Now you execute the forEach function passing the collection and the iterator and it should log each name from the collection.
  forEach(names, action); //  Logs -> 'John' 'Robert' 'James'

原生的forEach函数和我们刚刚创建的forEach函数之间的主要区别在于,你不需要将集合传递给它,因为Javascript将使用实际的对象(名称)作为你将迭代的集合。

 names.forEach(action); //  Logs -> 'John' 'Robert' 'James'

为了深入了解这个主题,我建议您阅读Eloquent Javascript书籍中的函数式编程章节

我希望它有所帮助。

for each ...in 语句已弃用为 ECMA-357 (E4X) 标准的一部分。E4X 支持已被删除,但对于每个...由于向后兼容性考虑,不会禁用和删除 in。考虑用于...的。

例:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8}; /* obj array with properties and values */
for each (var item in obj) {
sum += item;
}
console.log(sum); 

日志 "26",即 5+13+8,这里的 var 将迭代对象的 prop 值,例如 5,13,8...等,

这种循环在Java脚本中的一个重要用途是你不必关心数组或对象数组的索引,无论是数字还是字符串,Loop都会迭代!这在迭代对象中非常有用。