如何检查元素是否在JavaScript中的对象数组中?

时间:2018-09-02 07:55:57

标签: javascript arrays

我不知道为什么下面的代码总是出现在我的else语句而不是最初的if条件下。

var player = {
  inventory: [
    "Bullet"
  ],
};

function use() {
  alert(this); // Returns "Bullet"
  alert(player.inventory); // Returns "Bullet"
  if (this == player.inventory) {
    document.getElementById("inventory02").innerHTML = "You USED" + this;
    alert("in inventory"); // She skips this

  } else {
    document.getElementById("inventory02").innerHTML = "You don't have" + this;
    alert("not in inventory"); // She always does this
  }
}
<button id="use_bullet" onclick="use.call('Bullet')">Use Bullet</button>

2 个答案:

答案 0 :(得分:1)

  1. player.inentory是一个数组,您需要检查该项目是否在数组中 并且与之不相等。
  2. 这里使用thisconfusing(您将其串联起来,进行比较。。这是错误的),您可以传递一个参数,或者更好地传递一个参数,将一个属性保留在代表商品,然后use
  3. Array.includesnot supported in IE。如果您需要它在IE上运行并且不转换js代码(例如,使用Babel),则可以使用polyfillthis answer
  4. 我在alert中将console.log替换为,,因为该示例在示例中更加清晰(并且不那么烦人)。
  5. 在宣布库存后,您不需要额外的var player = { inventory: [ "Bullet" ] }; function use(e) { var item = e.target.getAttribute("item"); console.log(item); // Returns "Bullet" console.log(player.inventory); // Returns "Bullet" if (player.inventory.includes(item)) { document.getElementById("inventory02").innerHTML = "You USED " + item; alert("in inventory"); // She skips this } else { document.getElementById("inventory02").innerHTML = "You don't have " + item; alert("not in inventory"); // She always does this } }

<button id="use_bullet" item="Bullet" onclick="use(event)">Use Bullet</button>
<div id="inventory02"></div>
this

修改:
根据注释,您不希望使用HTML属性。我仍然建议在这种特殊情况下避免使用var player = { inventory: [ "Bullet" ] }; function use(item) { console.log(item); // Returns "Bullet" console.log(player.inventory); // Returns "Bullet" if (player.inventory.includes(item)) { document.getElementById("inventory02").innerHTML = "You USED " + item; alert("in inventory"); // She skips this } else { document.getElementById("inventory02").innerHTML = "You don't have " + item; alert("not in inventory"); // She always does this } }。这是我的建议:

<button id="use_bullet" onclick="use('Bullet')">Use Bullet</button>
<div id="inventory02"></div>
<assemblyRedirect

答案 1 :(得分:-1)

原因是它们的类型不同。 尝试使用.toString()

function use() {
    if (this.toString() === player.inventory.toString()) {
        alert("in inventory"); // She skips this

    } else {
        alert("not in inventory"); // She always does this
    }
}