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);
});
- 本文链接:https://archer-lan.github.io/2023/11/20/JavaScript%E5%9B%9E%E9%A1%BE-%E7%B4%A2%E5%BC%95%E9%9B%86%E5%90%88%E7%B1%BB/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。