[英]JavaScript if Statement Ignoring the Value of Some Variables, but not Others
I have some code for an object constructor of the form: 我有一些形式的对象构造函数的代码:
function objectConstructor(item, r) { //Pulls a string from elsewhere this.name = Object.ObjectOne[item].name; this.amount = Object.ObjectOne[item].amount; this.buttonID = pickButton(r); this.itemInitialCost = []; this.itemPriceIncrease = []; //This is the problematic area. if(this.name != "valueOne" || this.name != "valueTwo" || this.name != "valueThree" || this.name != "valueFour" || [...]) { for(var i = 0; i < Object.ObjectTwo[this.buttonID].cost.length; i++) { this.itemInitialCost.push(Object.ObjectTwo[this.buttonID].cost[i].initialCost; this.itemPriceIncrease.push(Object.ObjectTwo[this.buttonID].cost[i].costIncrease; } } else { this.itemInitialCost.push("none"); this.itemPriceIncrase.push("none"); } } function pickButton(r) { //The Function } var array = [Long List]; for(var i = 0; i < array.length; i++) { item = array[i]; items[item] = new objectConstructor(item, i); console.log("Created: " + item); } console.log(items);
The first 58 (of 67) item objects are created and assigned values just fine. 将创建前58个(共67个)项目对象,并为其分配值。 All items after the 58th don't have a buttonID, and therefore would throw errors when they tried to get their cost values.
第58位之后的所有商品都没有buttonID,因此在尝试获取费用值时会抛出错误。 To prevent this, I have the if statement set to assign those items (based on the item name) the value of "none" for cost.
为了防止这种情况,我将if语句设置为为这些项目(基于项目名称)分配值“ none”作为费用。 However, they seem to be ignoring the conditions in the if statement and going straight to the for loop that would set a normal items costs.
但是,他们似乎忽略了if语句中的条件,而直接进入将设置常规项成本的for循环。 They aren't going to the else statement, and are thereby causing my script to crash.
他们不打算执行else语句,从而导致我的脚本崩溃。
Why are they, apparently, ignoring the if statement's conditions? 他们为什么显然忽略了if语句的条件?
Any value for this.name
will evaluate to true for this: 为此,此
this.name
任何值都将评估为true:
this.name != "valueOne" || this.name != "valueTwo"
You probably want a &&
between those conditions. 您可能希望在这些条件之间使用
&&
。
Also, maybe it would make more sense to see if this
has some buttonID
rather than checking the name. 此外,也许会更有意义,看看
this
有一些buttonID
,而不是检查名称。
You want to use &&
instead of ||
您要使用
&&
而不是||
, as the latter (called OR
operator) only needs to satisfy one condition to evaluate to true (the former needs all). ,因为后者(称为
OR
运算符)只需要满足一个条件即可评估为真(前者需要全部)。 And If you have an array of those values and you want to make sure none of them matches this.name
, you can use the following instead of typing all the names out: 并且,如果您具有这些值的数组,并且想要确保没有一个与
this.name
匹配,则可以使用以下命令来代替键入所有名称:
if(arrayOfValues.indexOf(this.name)<0){
//assign special values
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.