简体   繁体   中英

How do I check if an element is in an array of an object in JavaScript?

I can't figure out why the following code always goes to my else statement, instead of my initial if condition.

 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>

  1. player.inentory is an array , you need to check if the item is in the array and not equal to it.
  2. The use of this here is confusing (you are concatenating it, comparing it.. it's just wrong), you can pass an argument instead or better yet, keep an attribute on the element that represents the item and use it.
  3. Array.includes is not supported in IE . If you need it to run on IE and you don't transpile your js code (with Babel for instance) you can use polyfill or this answer .
  4. I replaced the alert with console.log since it's more clear in the example (and less annoying).
  5. You don't need that extra , after the declaration of inventory.

 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>

Edit:
According to the comments you prefer not to use an HTML attribute. I would still recommend avoiding this in this particular situation. Here is my suggestion:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM