Getting an object from a class array in javascript
本问题已经有最佳答案,请猛点这里访问。
我有一个javascript类,
1 2 3 4 5 6 7 8 9 10 11 | class Snake{ constructor(id, trail){ this.velocityX = 0; this.velocityY = -1; this.trail = trail; this.id = id; } moveRight(){ console.log('move'); } } |
以及存储蛇对象的数组。
1 2 3 4 5 6 | 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)); |
例如,我想从ID为20的数组中删除元素。
我该怎么做?
这个怎么样?
1 | this.snakeList = this.snakeList.filter(x => x.id != 20); |
1 2 3 4 5 6 7 8 9 10 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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) |
看,这就是工作示例希望这有帮助
我会在这里使用拼接:
1 2 3 4 5 6 7 | for (var i = 0; i < snakes.length; i++) { var obj = snakes[i]; if (obj.id === 20) { snakes.splice(i, 1); i--; } } |
片段:
1 2 3 4 5 6 7 8 9 10 11 | 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) |