从 JS 中的不可变数组中删除元素的最干净方法是什么?
What is the cleanest way to remove an element from an immutable array in JS?
我需要从处于 React
组件状态的数组中删除一个元素。这意味着它是一个不可变对象。
使用展开语法可以轻松添加元素。
return {
...state,
locations: [...state.locations, {}]
};
删除有点棘手。我需要使用一个中间对象。
var l = [...state.locations]
l.splice(index, 1)
return {
...state,
locations: l
}
它使代码更脏,更难理解。
创建一个新数组并从中删除一个元素是否更容易或更不棘手?
您可以结合使用点差和 Array#slice:
const arr = ['a', 'b', 'c', 'd', 'e'];
const indexToRemove = 2; // the 'c'
const result = [...arr.slice(0, indexToRemove), ...arr.slice(indexToRemove + 1)];
console.log(result);
另一个选项是 Array#filter:
const arr = ['a', 'b', 'c', 'd', 'e'];
const indexToRemove = 2; // the 'c'
const result = arr.filter((_, i) => i !== indexToRemove);
console.log(result);
我需要从处于 React
组件状态的数组中删除一个元素。这意味着它是一个不可变对象。
使用展开语法可以轻松添加元素。
return {
...state,
locations: [...state.locations, {}]
};
删除有点棘手。我需要使用一个中间对象。
var l = [...state.locations]
l.splice(index, 1)
return {
...state,
locations: l
}
它使代码更脏,更难理解。
创建一个新数组并从中删除一个元素是否更容易或更不棘手?
您可以结合使用点差和 Array#slice:
const arr = ['a', 'b', 'c', 'd', 'e'];
const indexToRemove = 2; // the 'c'
const result = [...arr.slice(0, indexToRemove), ...arr.slice(indexToRemove + 1)];
console.log(result);
另一个选项是 Array#filter:
const arr = ['a', 'b', 'c', 'd', 'e'];
const indexToRemove = 2; // the 'c'
const result = arr.filter((_, i) => i !== indexToRemove);
console.log(result);