Saturday 23 July 2016

Getting an object from a class array in javascript




I have a javascript class like,



class Snake{

constructor(id, trail){
this.velocityX = 0;
this.velocityY = -1;
this.trail = trail;
this.id = id;
}
moveRight(){
console.log('move');
}
}



and an array that stores Snake objects.



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));



For example, I want to remove the element from the array which id is 20.



How can I do that?


Answer



What about this



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);




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...