【问题标题】:Getting an object from a class array in javascript [duplicate]从javascript中的类数组中获取对象[重复]
【发布时间】:2019-05-11 06:30:21
【问题描述】:

我有一个类似的 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 的元素。

我该怎么做?

【问题讨论】:

  • 使用过滤器将其删除?
  • 您在问 2 个问题。首先 - 是如何通过key/value 在数组中查找对象。第二 - 如何从数组中删除一个项目。

标签: javascript arrays


【解决方案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)

【讨论】:

    【解决方案2】:

    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)

    看这是工作示例 希望这会有所帮助

    【讨论】:

      【解决方案3】:

      这个呢

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

      【讨论】:

      • 谢谢,它成功了。现在我还有一个问题。如果我向蛇类添加任何方法,如“moveRight()”,我可以为特定蛇调用该方法吗?
      • 例如snakeList.filter(x => x.id == 22).moveRight();
      • if(snakeList.filter(x =&gt; x.id == 22).length){ moveRight();}
      • 好的对不起我的第二个问题。另外,谢谢您的回答。
      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 2021-09-14
      • 2020-10-02
      • 1970-01-01
      • 2012-12-07
      • 2023-03-20
      相关资源
      最近更新 更多