从 JS 中的不可变数组中删除元素的最干净的方法是什么?

IT技术 javascript arrays reactjs immutability spread-syntax
2021-03-31 19:58:14

我需要从作为React组件状态的数组中删除一个元素这意味着它是一个不可变的对象。

使用扩展语法可以轻松添加元素。

    return {
        ...state,
        locations: [...state.locations, {}]
    };

删除有点棘手。我需要使用一个中间对象。

        var l = [...state.locations]
        l.splice(index, 1)
        return {
            ...state,
            locations: l
        }

它使代码更脏,更难理解。

创建一个从中删除元素的新数组是否更容易或更不复杂?

1个回答

您可以结合使用 spread 和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);