方法汇总:
- 从数组尾部删除:
pop()
- 从数组头部删除:
shift()
- 按指定索引删除:
splice()
- 用
splice()
删除数组中的特定值
pop() 从Array 尾部删除元素
var numbers = [1,2,3,4,5];
numbers.pop(); // returns 5
console.log(numbers); // [1,2,3,4]
shift() 从Array 头部删除元素
var numbers = [1,2,3,4,5];
numbers.shift(); // returns 1
console.log(numbers); // [2,3,4,5]
splice() 按索引删除元素
splice(start, deleteCount)
方法中 start 表示要删除的元素的索引, deleteCount 表示要删除的元素的数量.
// Remove two elements from the second element of the array
var numbers = [1,2,3,4,5];
removed_nums = numbers.splice(1,2); //[2,3]
console.log(numbers); // [1,4,5];
用 splice() 删除数组中的特定值
简单的删除特定整数的例子
// Simple Example to remove a specific integer element from the array
var numbers = [1,2,3,4,5,6,7,8]
for(var i = 0; i < numbers.length; i++){
if( numbers[i] == 6){
numbers.splice(i,1);
}
}
// numbers = [1,2,3,4,5,7,8]
稍微复杂一点,自定义条件,删除 Object 类型元素的例子
// balls = [ball, ball, ball, ball, ball, blackhole]
// 遍历 balls 的数组, 如果 ball 碰到 BlackHole,则 ball 被移除
for (const [index, ball] of balls.entries()) {
if (!(this === ball)) {
const dx = this.x - ball.x;
const dy = this.y - ball.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.size + ball.size) {
if(this.name === "BlackHole"){
balls.splice(index,1);
}
}
}
}
参考资料
从JavaScript数组中移除元素的几种方法
Array.prototype.splice()
How to get the index from for-of loop with JavaScript