我有一个javascript类,
this.snakeList = new Array();
this.snakeList.push(new Snake(10, newSnakeTrail));
this.snakeList.push(new Snake(20, newSnakeTrail));
this.snakeList.push(new Snake(30, newSnakeTrail));
this.snakeList.push(new Snake(22, newSnakeTrail));
this.snakeList.push(new Snake(40, newSnakeTrail));
和一个存储Snake对象的数组。
{{1}}
例如,我要从ID为20的数组中删除元素。
我该怎么做?
答案 0 :(得分:5)
那
this.snakeList = this.snakeList.filter(x => x.id != 20);
let snakes = [{name: 'fuss', id: 10}, {name: 'huss', id: 20}, {name: 'hurr', id: 60}]
//Before removal
console.log("Before removal");
console.log(snakes);
snakes = snakes.filter(x => x.id != 20);
//After removal
console.log("After removal");
console.log(snakes);
答案 1 :(得分:0)
var snakeList = [
{
id:10,
trail:{}
},
{
id:20,
trail:{}
},
{
id:30,
trail:{}
}
]
snakeList.forEach((x,index)=>{
if(x.id === 20){
snakeList.splice(index,1)
}
})
console.log(snakeList)
看到这是工作示例 希望对您有帮助
答案 2 :(得分:-1)
我将在此处使用拼接:
for (var i = 0; i < snakes.length; i++) {
var obj = snakes[i];
if (obj.id === 20) {
snakes.splice(i, 1);
i--;
}
}
代码段:
let snakes = [{name: 'fuss', id: 10}, {name: 'huss', id: 20}, {name: 'hurr', id: 60}]
for (var i = 0; i < snakes.length; i++) {
var obj = snakes[i];
if (obj.id === 20) {
snakes.splice(i, 1);
i--;
}
}
console.log(snakes)