我不知道为什么下面的代码总是出现在我的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>
答案 0 :(得分:1)
player.inentory
是一个数组,您需要检查该项目是否在数组中 并且与之不相等。 this
是confusing(您将其串联起来,进行比较。。这是错误的),您可以传递一个参数,或者更好地传递一个参数,将一个属性保留在代表商品,然后use。Array.includes
是not supported in IE。如果您需要它在IE上运行并且不转换js代码(例如,使用Babel),则可以使用polyfill或this answer。 alert
中将console.log
替换为,
,因为该示例在示例中更加清晰(并且不那么烦人)。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
}
}