本文介绍了从JS中的不可变数组中删除元素的最干净方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to remove an element from an array that is a state of a React Component. Which means that it is an immutable object.

使用传播语法轻松添加元素.

Adding a element is easy using spread syntax.

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

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

Removing is a little more tricky. I need to use an intermediate object.

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

这使代码更加肮脏并且难以理解.

It make the code more dirt and difficult to understand.

创建一个新数组来删除其中的元素是否更容易或更轻松?

Is there an easier or less tricky to create a new array removing an element from it?

推荐答案

您可以使用点差和 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:

Another option is Array#filter:

const arr = ['a', 'b', 'c', 'd', 'e'];

const indexToRemove = 2; // the 'c'

const result = arr.filter((_, i) => i !== indexToRemove);

console.log(result);

这篇关于从JS中的不可变数组中删除元素的最干净方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 13:23