【JavaScript】`forEach` 方法的详解与实战
warning:
这篇文章距离上次修改已过230天,其中的内容可能已经有所变动。
forEach
方法对数组的每个元素执行一次给定的函数。
语法:
array.forEach(callback(currentValue, index, array){
// 执行的操作
}, this)
参数:
callback
:为数组中每个元素执行的函数,该函数接收以下三个参数:currentValue
:数组中正在处理的当前元素。index
:数组中正在处理的当前元素的索引。array
:正在操作的数组。
thisArg
(可选):执行callback
时用于this
的值。
返回值:
undefined
实例代码:
// 使用 forEach 计算数组中每个数的平方并打印
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(value, index, array) {
console.log(value * value);
});
// 使用箭头函数简化代码
numbers.forEach((value) => console.log(value * value));
// 使用 forEach 为对象的属性赋值
const obj = {a: 1, b: 2, c: 3};
const properties = [];
Object.keys(obj).forEach(function(key) {
properties.push({key: key, value: obj[key]});
});
console.log(properties); // [{key: 'a', value: 1}, ...]
评论已关闭