如何在Javascript中从数组中删除条目

How to delete an entry from my array in Javascript

本文关键字:删除 数组 Javascript      更新时间:2023-09-26

这个错误困扰了我大约2个小时。。。我正在制作一个空闲游戏,在这个游戏中,你可以拥有自己的城市,我现在正在创建一个建筑系统,问题是每当我从数组中删除(我有一个建筑队列,它保存要建造的建筑,然后将它们删除)时,游戏就会崩溃。我试过.shift.pop.push.indexOf(0) === 0[0] === "".splice(1,1),它只是想出了一个类似的函数。splice不是一个函数,或者.pop不是所有函数的函数。

什么都没用。请帮忙!

  if (buildValue === 100 && buildQueue.indexOf("house") === 0){
    populationmax++;
    // here i need a command that will remove first element from array called buildQueue.
    buildValue = 0;
  }

从阵列中删除

if (buildValue === 100 && buildQueue.indexOf("house") === 0){
  populationmax++;
  buildQueue.splice(0, 1); //removes first element
  buildValue = 0;
}

JS代码段

x = [1, 2, 3];
alert(x); //1,2,3
x.splice(0, 1);
alert(x); //2,3

添加到/创建阵列

首先,您不需要在buildQueue数组中放入空白字符串,这可能会在以后产生问题,只需执行以下操作:

buildQueue = [];

其次,您正尝试使用+=将字符串添加到数组中,就好像它是一个字符串一样。然而,这样做会将数组变成一个字符串,这就是为什么你会收到关于".splice()"的警告——你需要向数组中添加字符串,如下所示:

buildQueue.push(someString);

这样一来,buildQueue将保持为字符串数组。

var buildValue = 0,
    buildQueue = [""],
    buildSpeed = 1/200;
  if (buildQueue[0]){
    buildValue += buildSpeed;
  }
  if (buildValue >= 100){
    buildValue = 100;
  }
  if (buildValue === 100 && buildQueue.indexOf("house") === 0){
    populationmax++;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("big house") === 0){
    populationmax+=4;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("gold storage") === 0){
    goldmax++;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("food storage") === 0){
    foodmax++;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("wood storage") === 0){
    woodmax++;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("stone storage") === 0){
    stonemax++;
    buildValue = 0;
  }
  if (buildValue === 100 && buildQueue.indexOf("iron storage") === 0){
    ironmax++;
    buildValue = 0;
  }
  buildSpeed = 0.2;

这就是我所要做的全部构建。此外,若你们购买了一栋建筑,它只会添加到阵列中。例如,gold存储将添加buildQueue += "gold store";,并且假设if内部的行之间的空格具有删除[0]元素的命令。