有没有更优雅的方法从数组中删除元素?

问题描述 投票:0回答:3

我现在从数组中删除元素的方法是这样的

var indexToRemove = newSections.indexOf(newSections.find((section) => section.id === parseInt(sectionId)));
newSections.splice(indexToRemove, 1);

但是,我希望能够删除我的元素。

array.remove(element)

我怎样才能完成这样的事情?

javascript
3个回答
2
投票

没有API来做这样的事情,但你可以用Array.filter做类似的事情。

let words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

words = words.filter(word => word != "spray");

在上面的例子中,words不包含单词spray


1
投票

如果您想要进行删除,可以使用reduce做得更好:

var indexToRemove = newSections.reduce(
    (acc,section,index) =>
        (acc === null && section.id === parseInt(sectionId) ? index : acc),
    null);
if (indexToRemove !== null)
    newSections.splice(indexToRemove, 1);

所以你的数组只被解析一次。

否则我更喜欢与find的答案


1
投票

假设如下

sections = [
    {id: 1, name: 'section 1'},
    {id: 2, name: 'section 2'},
    {id: 3, name: 'section 3'}
]

定义简单的功能

function removeSection(sections, sectionIdToRemove) {
  return sections.filter(s=>s.id != parseInt(sectionIdToRemove)
}

用它

removeSection(sections, 1) // removes the second section

不建议将这样的.remove方法添加到全局Array对象中。

© www.soinside.com 2019 - 2024. All rights reserved.