// 使用 Array.prototype.map 方法对数组中的每个元素执行指定的操作,并返回一个新数组
const numbers = [1, 2, 3, 4];
// 将数组中的每个元素乘以 2
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // 输出: [2, 4, 6, 8]
// 使用箭头函数简化代码
const squared = numbers.map(num => num * num);
console.log(squared); // 输出: [1, 4, 9, 16]
Array.prototype.map 是 JavaScript 中的一个高阶函数,它会遍历数组中的每一个元素,并对每个元素执行传入的回调函数。numbers,然后使用 map 方法将每个元素乘以 2,生成了一个新的数组 doubled。squared。上一篇:js string 转int
下一篇:js array.map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站