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

标签 javascript arrays reactjs immutability spread-syntax

<分区>

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

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

    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);

关于javascript - 从 JS 中的不可变数组中删除元素的最干净方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023975/

相关文章:

javascript - 使用 Javascript 存储 session 显示在 ASP.NET C# 中另一个页面的标签中

javascript - CoffeeScript + Express : unexpected ,

javascript - 在 Angular 1.5 中刷新浏览器时如何保留同一页面?

Javascript多维数组不起作用

arrays - 在数组 VBA 中查找特定 Object.Name 字符串的快速方法

reactjs - 应用程序在运行时抛出错误 [SyntaxError : Unexpected token import]

javascript - jquery.flash 插件在 IE6 中不工作

python - 迭代将列附加到python中的数组

reactjs - Material UI - 打开弹出窗口时取消阻止滚动

javascript - 失败的 prop 类型 : Invalid prop `onClick` of type `object` supplied to `Button` , 预期 `function`