在JavaScript中,我们可以结合使用indexOf()
和splice()
从数组中删除某个元素。
var array = [1, 2, 3, 4, 5];
console.log(array)
// I want remove num 4, find the index first, -1 if it is not present.
var index = array.indexOf(4);
if (index > -1) { // found
array.splice(index, 1);
}
// array = [1, 2, 3, 5];
console.log(array);
var lang = ['java', 'node js', 'javascript', 'pyhton'];
console.log(lang)
// I want remove node js
var index = lang.indexOf(`node js`);
if (index > -1) {
lang.splice(index, 1);
}
//lang = ['java', 'javascript', 'pyhton'];
console.log(lang);
参考文献
标签: 数组 javascript