为什么 JavaScript 数组中没有 Straighfoward "remove" 方法?



我对javascript不是很有经验。我一直有一个问题:为什么javascript数组没有remove()方法?

有这样的API不是很好吗:

remove(index):按索引删除项目,返回已删除元素

remove(func):删除与函数指定的条件匹配的项,并返回已删除项的数组,例如:

let deleteStudents = studentArray.remove(s => s.age < 18);

那么,为什么javascript中没有这样有用的方法,而我们不得不使用非直观的splice方法呢?

有。但函数名为splice

删除索引n:处的项目

myArray.splice( n, 1 );

对于按索引删除,请使用Array.splice(index, remove_count)方法。示例

var words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];
// We will remove the item in index 1. (limit)
words.splice(1, 1);
console.log(words);
// prints [ 'spray', 'elite', 'exuberant', 'destruction', 'present' ]

要通过函数删除,请使用filter方法:它基于函数创建一个新数组。示例:

var words = [‘spray’, ‘limit’, ‘elite’, ‘exuberant’, ‘destruction’, ‘present’];
// Removes words having length less than 6
const result = words.filter(word => word.length < 6); 
console.log(result); // prints [ 'spray', 'limit', 'elite' ]

最新更新