// 示例代码:替换数组中的特定元素
// 原始数组
let arr = [1, 2, 3, 4, 5];
// 替换数组中特定位置的元素
arr[2] = 'newElement'; // 将索引为2的元素(即原来的3)替换为'newElement'
console.log(arr); // 输出: [1, 2, "newElement", 4, 5]
// 使用 map 方法替换满足条件的元素
let arr2 = [1, 2, 3, 4, 5];
let newArr2 = arr2.map(item => item === 3 ? 'replaced' : item);
console.log(newArr2); // 输出: [1, 2, "replaced", 4, 5]
// 使用 findIndex 和 splice 方法替换满足条件的元素
let arr3 = [1, 2, 3, 4, 5];
let index = arr3.findIndex(item => item === 3);
if (index !== -1) {
arr3.splice(index, 1, 'replaced');
}
console.log(arr3); // 输出: [1, 2, "replaced", 4, 5]
map
方法:遍历数组并根据条件替换元素,返回一个新的数组。findIndex
和 splice
方法:先找到满足条件的元素索引,然后使用 splice
方法在该索引处插入新元素并移除旧元素。上一篇:js 数组替换元素
下一篇:js 移除数组元素
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站