【问题标题】:What is the cleanest way to remove an element from an immutable array in JS? [duplicate]从 JS 中的不可变数组中删除元素的最干净的方法是什么? [复制]
【发布时间】:2018-04-11 22:44:40
【问题描述】:

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

使用展开语法很容易添加元素。

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

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

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

它使代码更加肮脏且难以理解。

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

【问题讨论】:

  • const arr = ['a', 'b', 'c', 'd', 'e']; delete arr[2]; console.log(arr.filter(Array))
  • @zerkms 我觉得这个问题比重复问题好,因为这与使用的库无关,而欺骗目标的答案被 Redux 语法污染。
  • @EmileBergeron 标记的答案与 redux 的连接为 0,并且是通用 JS。第二个答案中的第一个示例是通用 JS。对我来说 - 它看起来很适合愿意学习而不是复制粘贴的人。

标签: javascript arrays reactjs immutability spread-syntax


【解决方案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);

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 2011-06-17
    • 1970-01-01
    • 2015-01-19
    • 2011-03-12
    • 2011-06-28
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多