javascript - 从javascript中的类数组获取对象

标签 javascript arrays

<分区>

我有一个 javascript 类,比如,

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

和一个存储 Snake 对象的数组。

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的元素。

我该怎么做?

最佳答案

这个呢

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

关于javascript - 从javascript中的类数组获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704277/

相关文章:

javascript - Lodash - 根据条件合并两个数组的对象

javascript - Yii ajaxbutton : How to get $(this) in success callback function?

javascript - 从 Bootstrap 日期时间选择器中选择后将日期加载到输入字段

java - JAVA取N个数组并将其转换为具有N行的多维数组

javascript - 无法从 firebase 获取嵌套子级的数据?

javascript - 如何在循环内以编程方式命名 1000 个文本框

java - 冒泡排序模块似乎不起作用;输出错误列表(java)

arrays - Fortran 中计算分量张量变化的有效方法

php - 了解数组符号(特别是 mysql_fetch_array 和 print_r)

python - 检查字符串是否包含 Python 数组中的多个元素