数组迭代起方法与迭代方法
在 ES6 中,Array 的原型上暴露了 3 个用于检索数组内容的方法:keys()、values()和 entries()。keys()返回数组索引的迭代器,values()返回数组元素的迭代器,而 entries()返回 索引/值对的迭代器:
const a = ["foo", "bar", "baz", "qux"]; // 因为这些方法都返回迭代器,所以可以将它们的内容 // 通过 Array.from()直接转换为数组实例
const aKeys = Array.from(a.keys()); const aValues = Array.from(a.values()); const aEntries = Array.from(a.entries()); console.log(aKeys); // [0, 1, 2, 3] console.log(aValues); // ["foo", "bar", "baz", "qux"] console.log(aEntries); // [[0, "foo"], [1, "bar"], [2, "baz"], [3, "qux"]]
使用 ES6 的解构可以非常容易地在循环中拆分键/值对:
const a = ["foo", "bar", "baz", "qux"]; for (const [idx, element] of a.entries()) { alert(idx); alert(element); } // 0 // foo // 1 // bar // 2 // baz // 3 // qux
ECMAScript 为数组定义了 5 个迭代方法。
每个方法接收两个参数:以每一项为参数运行的函数,
以及可选的作为函数运行上下文的作用域对象(影响函数中 this 的值)。传给每个方法的函数接收 3
个参数:数组元素、元素索引和数组本身。因具体方法而异,这个函数的执行结果可能会也可能不会影
响方法的返回值。数组的 5 个迭代方法如下。
every():对数组每一项都运行传入的函数,如果对每一项函数都返回 true,则这个方法返回 true。
filter():对数组每一项都运行传入的函数,函数返回 true 的项会组成数组之后返回。
forEach():对数组每一项都运行传入的函数,没有返回值。
map():对数组每一项都运行传入的函数,返回由每次函数调用的结果构成的数组。
some():对数组每一项都运行传入的函数,如果有一项函数返回 true,则这个方法返回 true。