简体   繁体   English

javascript中forEach和for循环的区别

[英]Difference between forEach and for loop in javascript

I am wondering: Is there any significant difference between forEach and for loop in JavaScript.我想知道:JavaScript 中的forEachfor循环之间是否存在显着差异。

Consider this example:考虑这个例子:

var myArray = [1,2,3,4];

myArray.forEach(function(value) {
  console.log(value);
});

for (var i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

Here is part of my research:这是我研究的一部分:

  1. Performance : According to JsPerf : forEach is little slower than for loop.性能:根据JsPerf :forEach 比 for 循环慢一点。
  2. Usability : There is no way we can break/return from the callback in case of forEach loop.可用性:在 forEach 循环的情况下,我们无法从回调中中断/返回。

For example: You want to find out if a number is prime or not.例如:你想知道一个数字是否是素数。 I think using for loop is much more easier than using forEach loop to do this.我认为使用 for 循环比使用 forEach 循环更容易做到这一点。

  1. Readability: Using for loop makes code more readable than having forEach in code.可读性:使用 for 循环使代码比在代码中使用 forEach 更具可读性。
  2. Browser compatibility : forEach is Not supported in IE < 9 So that introduces some shim in our code.浏览器兼容性: IE < 9 不支持 forEach 因此在我们的代码中引入了一些 shim。

My questions are:我的问题是:

  1. What are the advantages of forEach over for loop? forEach 相对于 for 循环的优势是什么?
  2. In what scenarios, forEach is more preferable.在什么场景下,forEach 更可取。
  3. Why did even it come into JavaScript?为什么它甚至会进入JavaScript? Why was it needed at all?为什么需要它?

forEach is a method on the Array prototype. forEachArray原型上的一个方法。 It iterates through each element of an array and passes it to a callback function.它遍历数组的每个元素并将其传递给回调函数。

So basically, forEach is a shorthand method for the use-case "pass each element of an array to a function " .所以基本上, forEach是用例“将array每个元素传递给function的速记方法。 Here is a common example where I think Array.forEach is quite useful, compared to a for loop:这是一个常见的例子,我认为Array.forEachfor循环相比非常有用:

// shortcut for document.querySelectorAll
function $$(expr, con) {
    return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}

// hide an element
function hide(el) {
    el.style.display = 'none';
}

// hide all divs via forEach
$$('div').forEach(hide); 

// hide all divs via for
for (var divs = $$('div'), i = 0; i < divs.length; i++) {
    hide(divs[i])
}

As you can see, the readability of the forEach statement is improved compared to a for loop.如您所见,与for循环相比,forEach 语句的可读性得到了提高。

On the other hand, a for statement is more flexible: it does not necessarily involve an array.另一方面, for语句更灵活:它不一定涉及数组。 The performance of a normal for loop is slightly better, because there is no function call for each element involved.普通for循环的性能稍好一些,因为没有对涉及的每个元素进行函数调用。 Despite of this, it is recommended to avoid for loops when it can be written as a forEach statement.尽管如此,建议在可以将其编写为forEach语句时避免for循环。

In a forEach loop you don't control the way you iterate over the array.forEach循环中,您无法控制迭代数组的方式。 The classic for loop allows you to choose the iteration algorithm as you want ( i++ ; i-- ; i+=2*i , etc).经典的for循环允许您根据需要选择迭代算法( i++i--i+=2*i等)。

However, a forEach loop is much easier to use - you don't need to mess with all the i counting, finding the array[i] object -- JS does it for you.但是, forEach循环使用起来要容易得多——你不需要搞乱所有的i计数,找到array[i]对象——JS 为你做。

>> sparseArray = [1, 2, , 4];

>> sparseArray.forEach(console.log, console);
1 0 [1, 2, 3: 4] 
2 1 [1, 2, 3: 4] 
4 3 [1, 2, 3: 4] 

>> for(var i = 0; i < sparseArray.length; ++i) { console.log(sparseArray[i]) };
1
2
undefined
4 

forEach is a recent addition to make expressive list-comprehension style possible in javascript. forEach是最近添加的,用于在 javascript 中实现富有表现力的列表理解风格。 Here you can see that forEach skips elements that were never set , but the best you can do with a for loop is to check for undefined or null , both of which can be set as values and picked up by forEach .在这里您可以看到forEach跳过了从未设置过的元素,但是使用for循环可以做的最好的事情是检查undefinednull ,这两者都可以设置为值并由forEach Unless you expect missing values, forEach is equivalent to for loops, but note that you cannot stop early, for which you need every .除非您期望缺少值,否则forEach等效于for循环,但请注意您不能提前停止,为此您需要every

In simple terms, according to the below article, and research, it seems that the main differences are:简单来说,根据下面的文章和研究,主要区别似乎是:

For Loop For循环

  1. It's one of the original ways of iterating over arrays这是迭代数组的原始方法之一
  2. It's faster它更快
  3. You could break out of it using this keyword你可以break的它使用该关键字
  4. In my opinion its mainly used for calculations with integers (numbers)在我看来它主要用于计算整数(数字)
  5. The parameters are (iterator, counter, incrementor)参数是(iterator, counter, incrementor)

ForEach Loop ForEach 循环

  1. It's a newer way with less code to iterate over arrays这是一种更新的方法,用更少的代码来迭代数组
  2. Easier to read更容易阅读
  3. Lets you keep variable within the scope让你在范围内保持变量
  4. Lower chance of accidental errors with the i <= >= etc.....使用i <= >= etc.....降低意外错误的机会i <= >= etc.....
  5. The parameters are (iterator, Index of item, entire array)参数是(iterator, Index of item, entire array)

https://alligator.io/js/foreach-vs-for-loops/ https://alligator.io/js/foreach-vs-for-loops/

Here is a difference between forEach and for loop in JavaScript.这是 JavaScript 中 forEach 和 for 循环之间的区别。

Performance wise, I prefer the for loop over the forEach loop.性能方面,我更喜欢 for 循环而不是 forEach 循环。 This is just one of some issues I have come across with the forEach loop.这只是我在 forEach 循环中遇到的一些问题之一。

let abc = [1,2,3] 

abc.forEach((e) => { 
   delete e; 
}) 

console.log(abc)  //Array(3) [ 1, 2, 3 ]

for (let i = 0; i < abc.length; i++) { 
   delete abc[i]; 
} 

console.log(abc)  //Array(3) [ <3 empty slots> ]

Apart from flexibility, one main reason why I would use the for loop is if I needed to break out of a loop early.除了灵活性,为什么我会用一个主要原因for循环是,如果我需要break早期循环出来。

In the below sample code if you wanted to only return a certain value in your array, you could use an if statement to check if your criteria matchs, and then break out from the loop.在下面的示例代码中,如果您只想返回数组中的某个value ,您可以使用if语句来检查您的条件是否匹配,然后退出循环。 The forEach method would iterate over each food, which could lead to performance issues. forEach方法会迭代每种食物,这可能会导致性能问题。

//Assume that foodArray has been declared
for (let i = 0; i < foodArray.length; i++) {
  if (foodArray[i].name === 'Pizza') {
    console.log('PIZZA EXISTS');
    break;
  }
}

forEach为每个

  1. forEach is a method on the Array prototype. forEach 是 Array 原型上的一个方法。
  2. It is easy to use这个用起来很简单
  3. It contains a callback function and each element from array is passed to callback function它包含一个回调函数,数组中的每个元素都传递给回调函数
  4. Because of callback, You can not use await with forEach ,it will lead to different output than expected.由于回调,您不能将 await 与 forEach 一起使用,这将导致与预期不同的输出。
  5. Because of callback function it is slower than for loop由于回调函数,它比 for 循环慢
  6. Because of callback you can not use break由于回调,您不能使用 break

For loop For 循环

  1. In for loop you need an index, condition and increment/decrement of index variable在 for 循环中,您需要索引变量的索引、条件和增量/减量
  2. It is faster than foreach它比 foreach 快
  3. You can use break您可以使用中断
  4. It works with await它适用于等待

forEach is a method on Array prototype which intakes a function expression that it executes on each iteration and within this function, the current iterated item of the Array is passed as the first argument. forEachArray原型上的一个方法,它接收一个 function 表达式,它在每次迭代中执行,在这个 function 中,Array 的当前迭代项作为第一个参数传递。 ForEach structure: ForEach 结构:

// Arrow function
forEach((element) => { /* … */ })
forEach((element, index) => { /* … */ })
forEach((element, index, array) => { /* … */ })

On the other hand, A for loop is a construct inherent to JavaScript language itself.另一方面, for循环是 JavaScript 语言本身固有的构造。 For loop repeats until a specified condition evaluates to false. For循环重复,直到指定条件评估为假。 Arrays operations are one thing that can be used within this for loop body but not necessarily the only thing whereas forEach works only with Array. Arrays 操作是可以在这个for循环体中使用的一件事,但不一定是唯一的事情,而forEach仅适用于 Array。

For loop structure: For循环结构:

for ([initialExpression]; [conditionExpression]; [incrementExpression]) {



 statement



}

For loop is slightly better than ForEach in performance but it is advised to use forEach whenever it can for more readable code. For循环的性能略好于ForEach ,但建议尽可能使用forEach以获得更易读的代码。

From: Eric Sarrion's Book “JavaScript from Frontend to Backend.”:来自:Eric Sarrion 的书“JavaScript 从前端到后端”:

The difference between the for() loop and the forEach() method for() 循环和 forEach() 方法的区别

To show the difference between these two approaches (the for() loop and forEach() method ), let's introduce a new element in the array, at index 10, knowing that the last index used during the creation of the array was 4. We thus create a new element that is much further away than the current last element of the array.为了展示这两种方法( for()循环forEach() 方法)之间的区别,让我们在数组中引入一个新元素,在索引 10 处,知道在创建数组期间使用的最后一个索引是 4。我们因此创建一个比数组的当前最后一个元素更远的新元素。 How will the array react to this enlargement?阵列将如何应对这种扩大?

// original array
var tab = ["Element 1", "Element 2", "Element 3", "Element 4", 
"Element 5"];

// adding a new element in the array, at index 10
tab[10] = "Element 9";
console.log("tab =", tab);

// display the array with a for() loop
console.log("Access to each element by a for() loop");
for (var i = 0; i < tab.length; i++) console.log("tab[" + i + "]=", tab[i]);

// display the array by the forEach() method
console.log("Access to each element by the forEach() method");
tab.forEach(function(elem, i) {
 console.log("tab[" + i + "]=", elem);
});

We add an element to the array using tab[10] = "Element 9", then display the contents of the array using the for() loop and then the forEach() method .我们使用 tab[10] = "Element 9" 向数组添加一个元素,然后使用for() 循环forEach() 方法显示数组的内容。 The result is displayed in the following figure:结果如下图所示:

在此处输入图像描述

The display of the for() loop shows that the elements with indices 5 to 9 exist but are of value undefined, because effectively, no values have been inserted for these indices of the array. for() 循环的显示显示具有索引 5 到 9 的元素存在但值未定义,因为实际上,没有为数组的这些索引插入任何值。 However, the indices 5 to 9 with their undefined values are displayed by the for() loop .但是,索引 5 到 9 及其未定义的值由for() 循环显示。

Conversely, the forEach() method provides the callback function indicated in parameters with only the array elements that have actually been affected in the array.相反, forEach() 方法提供的回调 function 在参数中仅包含数组中实际受到影响的数组元素。 This therefore avoids the elements at indices 5 to 9, which have not been assigned in the program.因此,这避免了未在程序中分配的索引 5 到 9 处的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM