在 JavaScript 中,有几种方法可以替换数组中的特定值。以下是常用的几种方式:
indexOf()
和索引赋值const fruits = ['apple', 'banana', 'orange', 'apple'];
const index = fruits.indexOf('apple'); // 找到第一个匹配项的索引
if (index !== -1) {
fruits[index] = 'pear'; // 替换值
}
console.log(fruits); // ['pear', 'banana', 'orange', 'apple']
splice()
方法const numbers = [1, 2, 3, 4, 5];
const index = numbers.indexOf(3);
if (index !== -1) {
numbers.splice(index, 1, 30); // 在索引位置删除1个元素并插入新值
}
console.log(numbers); // [1, 2, 30, 4, 5]
map()
方法(替换所有匹配项)const colors = ['red', 'blue', 'green', 'blue'];
const newColors = colors.map(color => color === 'blue' ? 'yellow' : color);
console.log(newColors); // ['red', 'yellow', 'green', 'yellow']
findIndex()
和替换(适用于对象数组)const users = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'},
{id: 3, name: 'Bob'}
];
const index = users.findIndex(user => user.id === 2);
if (index !== -1) {
users[index] = {id: 2, name: 'Janet'}; // 替换整个对象
}
console.log(users);
const items = ['a', 'b', 'c', 'd'];
const newItems = [...items.slice(0, 2), 'x', ...items.slice(3)];
console.log(newItems); // ['a', 'b', 'x', 'd']
map()
方法最为简洁array[index] = newValue
) 性能最好您可以根据具体需求选择最适合的方法。