繁体   English   中英

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

[英]Is there a more elegant way to remove a element from an array?

我现在从数组中删除元素的方式是

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

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

array.remove(element)

我该如何完成这样的事情?

没有API可以执行此操作,但是您可以使用Array.filter进行类似的Array.filter

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

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

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

如果要就地删除,可以通过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的答案

假设以下

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对象中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM