JavaScript回顾-索引集合类

forEach方法

const colors = ['red', 'green', 'blue'];
colors.forEach((color) => console.log(color));
// red
// green
// blue

传递给 forEach 的函数对数组中的每个元素执行一次,数组元素作为参数传递给该函数。未赋值的值不会在 forEach 循环迭代。

在数组定义时省略的元素不会在 forEach 遍历时被列出,但是手动赋值为 undefined 的元素是会被列出的。

map方法

方法返回由每个数组元素上执行callback的返回值所组成的新数组

const a1 = ['a', 'b', 'c'];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']

使用类数组对象

一些JavaScript对象,例如document.getElementByTagName()返回的NodeList或者函数内部可用的arguments对象。表面上看起来,外观和行为像数组,但是不共享它们所有的方法。

Array的原生(prototype)方法可以用来处理类似数组行为的对象,如:

function printArguments() {
  Array.prototype.forEach.call(arguments, function(item) {
    console.log(item);
  });
}

Array 的常规方法也可以用于处理字符串,因为它提供了序列访问字符转为数组的简单方法:

Array.prototype.forEach.call("a string", function(chr) {
  console.log(chr);
});