我现在从数组中删除元素的方法是这样的
var indexToRemove = newSections.indexOf(newSections.find((section) => section.id === parseInt(sectionId)));
newSections.splice(indexToRemove, 1);
但是,我希望能够删除我的元素。
array.remove(element)
我怎样才能完成这样的事情?
没有API来做这样的事情,但你可以用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
对象中。