// 使用 forEach 的示例
const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
console.log(`Index ${index}: ${num}`);
arr[index] = num * 2;
});
console.log(numbers); // 输出: [2, 4, 6, 8]
// 使用 map 的示例
const numbers2 = [1, 2, 3, 4];
const doubled = numbers2.map((num) => {
return num * 2;
});
console.log(doubled); // 输出: [2, 4, 6, 8]
console.log(numbers2); // 输出: [1, 2, 3, 4]
// 解释说明:
// forEach 是用来遍历数组中的每个元素,它不会返回新的数组,只能修改原数组。
// map 也是用来遍历数组中的每个元素,但它会返回一个新的数组,原数组保持不变。
上一篇:js map对象遍历
下一篇:js map取值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站