我有一个对象数组,它有一个position属性沿着其他属性,如下所示:
[{position: 1, ...otherProperties}, ...otherObjects]
在前端,对象按其位置显示和排序。
我正在寻找JavaScript函数来执行以下操作:
1.在指定的位置插入一个新对象(例如,在具有position的元素之前:1),并相应地更新其他元素的位置(例如,先前位置:1元素现在将是位置:2)。
1.从指定位置删除对象并相应地更新其余元素的位置。
我正在为这些功能的创建而挣扎
我有一个对象数组,它有一个position属性沿着其他属性,如下所示:
[{position: 1, ...otherProperties}, ...otherObjects]
在前端,对象按其位置显示和排序。
我正在寻找JavaScript函数来执行以下操作:
1.在指定的位置插入一个新对象(例如,在具有position的元素之前:1),并相应地更新其他元素的位置(例如,先前位置:1元素现在将是位置:2)。
1.从指定位置删除对象并相应地更新其余元素的位置。
我正在为这些功能的创建而挣扎
2条答案
按热度按时间lymnna711#
您可以创建两个函数
addElement
和removeElement
来添加或删除数组中的元素,同时确保位置正确排序。例如:使用方法:
zzlelutf2#
您需要一个方法来解析数组的所有项并将新位置设置为所有项。