【问题标题】:JavaScript if Statement Ignoring the Value of Some Variables, but not OthersJavaScript if 语句忽略某些变量的值,但不忽略其他变量的值
【发布时间】:2015-04-19 06:22:40
【问题描述】:

我有一些形式的对象构造函数的代码:

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);

创建前 58 个(共 67 个)项目对象并为其赋值。 58 号之后的所有项目都没有 buttonID,因此在尝试获取成本值时会抛出错误。为了防止这种情况,我设置了 if 语句来为这些项目(基于项目名称)分配成本的“无”值。但是,他们似乎忽略了 if 语句中的条件并直接进入设置正常项目成本的 for 循环。他们不会去 else 语句,从而导致我的脚本崩溃。

为什么他们显然忽略了 if 语句的条件?

【问题讨论】:

    标签: javascript if-statement conditional-statements


    【解决方案1】:

    this.name 的任何值都将评估为 true:

    this.name != "valueOne" || this.name != "valueTwo"
    

    您可能希望在这些条件之间使用&amp;&amp;

    另外,也许查看 this 是否有一些 buttonID 而不是检查名称更有意义。

    【讨论】:

    • 为什么他们评估为真?
    • 假设您正在检查名称"valueOne"。该语句转换为"valueOne" != "valueOne" || "valueOne" != "valueTwo" -> false || true -> true
    【解决方案2】:

    您想使用&amp;&amp; 而不是||,因为后者(称为OR 运算符)只需要满足一个条件即可评估为真(前者需要全部)。如果你有一个包含这些值的数组,并且你想确保它们都不匹配this.name,你可以使用以下命令而不是输入所有名称:

    if(arrayOfValues.indexOf(this.name)<0){
        //assign special values
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 1970-01-01
      • 2013-02-28
      • 2012-08-12
      • 2020-09-03
      • 2014-03-04
      • 2022-12-06
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多