3

JavaScript 中的 .forEach() 和 for…of

 2 years ago
source link: https://www.techug.com/post/in-javascript-foreach-and-for-of.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript 中的 .forEach() 和 for…of

2



img16393587051838120882.png

.forEach() 方法被认为是 JavaScript 中的高阶函数,其工作方式是为列表中的每个元素传入当前元素、索引和列表(正在循环的整个数组),用更专业的术语来说就是对于迭代器的每次调用,函数都会接收三个参数(元素、索引、列表)调用。如果列表是 JavaScript 对象,则迭代器参数将是 (valuekeylist)。在现代前端开发中,通常 .forEach() 方法可以替代过去的 for ,而对于不需要访问索引的遍历则建议使用 for...of ,因为它的遍历效率比 .forEach() 快。

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

  • callback:为数组中每个元素执行的函数,该函数接收一至三个参数:

  • currentValue:数组中正在处理的当前元素。

  • index:可选,数组中正在处理的当前元素的索引。

  • array:可选,forEach() 方法正在操作的数组。

使用方法如下代码:

const arrayMonths = ["一月", "二月", "三月"];
arrayMonths.forEach((value, index, list) => {
    console.log(value); // 一月,二月,三月
    console.log(index); // 0,1,1
    console.log(list); // [ '一月', '二月', '三月' ],[ '一月', '二月', '三月' ],[ '一月', '二月', '三月' ]
});

说到 .forEach() ,就有必要提一下 for...of ,一个 ES6 中也引入用于迭代列表的方法。

for (variable of iterable) {
    //statements
}

  • variable:在每次迭代中,将不同属性的值分配给变量。

  • iterable:被迭代枚举其属性的对象。

const arrayMonths = ["一月", "二月", "三月"];
for (const month of arrayMonths) {
    console.log(month); // 一月,二月,三月
}

.forEach() 与 for…of

.forEach() 函数在数组上循环并在每次迭代中执行回调函数,使用 .forEach() 方法和使用 for...of 之间没有功能区别。.forEach() 的一个好处是可以访问索引,而 for...of 不会访问索引。

for...of 支持循环体中的各种控制流,如 continuebreakyieldawait

在效率上,for...of.forEach() 快。

在代码组织上,如果 for…of 中代码量很大的时候,维护起来会非常麻烦,循环中的代码也与它紧密耦合,降低了它的可重用性。

当使用 .forEach() 循环时,可以像下面这样组织代码:

const arrayMonths = ["一月", "二月", "三月"];


function printValue(value) {
    console.log(value);
}


arrayMonths.forEach(printValue);

通常有人会问如何中止 .forEach()

默认情况下,是无法取消 .forEach() 循环。但是,可以使用的一种方法是放置一个“假”循环中断——也就是说,在逻辑周围放置一个条件,以便仅在条件匹配时才执行。

const arrayMonths = ["一月", "二月", "三月"];


function printValue(value) {
    if (value === "二月") {
        console.log(value);
    }
}


arrayMonths.forEach(printValue);

上面的代码片段只是一种循环中断的假象,在这种情况下就需要使用 .find().filter().findIndex() 来替代。

本文文字及图片出自 InfoQ


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK