【问题标题】:Udacity Murder Mystery - javascript not saving variableUdacity 谋杀之谜 - javascript 不保存变量
【发布时间】:2025-11-30 05:45:01
【问题描述】:

这是我在 Stack Overflow 上的第一个问题,也是我遇到的第一个问题。

    var room = "ballroom";
    var suspect = "Mr. Kalehoff";
    
    var weapon = "";
    var solved = true;
    
    if (room === "dining room" && suspect === "Mr. Parkes") {
        weapon === "knife";
        solved === true;
    } else if (room === "gallery") {
        weapon === "trophy";
        solved === true;
    } else if (room === "ballroom" && suspect === "Mr. Kalehoff") {
        weapon === "pool stick";
        solved === true;
    } else {
        weapon === "poison";
        solved === false;
    }
    
    if (solved) {
    	console.log(suspect + " did it in the " + room + " with the " + weapon + "!");
    }

在上面的 javascript 代码中,变量 weaponsolved 的值不会保存并反映在控制台上,即使我已经更改了 room怀疑满足条件;该语句将不起作用。

对此的任何帮助将不胜感激。 希望这一切都有意义。 干杯!

【问题讨论】:

  • 你能发个sn-p吗?
  • @KrishnaPrashatt OP 做到了。
  • 这是一个代码.. 我要的是 sn-p
  • 使用= 分配一个变量。仅在尝试比较时使用===
  • 那么solved === true;到底应该是什么?您没有将任何内容保存到变量 solvedweapon === <xxxx> 也是如此)

标签: javascript variables if-statement


【解决方案1】:

在 if & else 中,您需要使用单个 = 分配值

var room = "ballroom";
var suspect = "Mr. Kalehoff";

var weapon = "";
var solved = true;

if (room === "dining room" && suspect === "Mr. Parkes") {
  weapon = "knife"; //changed here
  solved = true;    //changed here
} else if (room === "gallery") {
  weapon = "trophy";   //changed here
  solved = true;       //changed here
} else if (room === "ballroom" && suspect === "Mr. Kalehoff") {
  weapon = "pool stick";   //changed here
  solved = true;           //changed here
} else {
  weapon = "poison";       //changed here
  solved = false;          //changed here
}

if (solved) {
  console.log(suspect + " did it in the " + room + " with the " + weapon + "!");
}

【讨论】:

    【解决方案2】:

    对于变量的赋值操作(或保存)值,您必须使用单个 = 符号。
    更多关于赋值操作的参考
    1.w3schools

    2.developer.mozilla

    所以用

    weapon = "knife";
    solved = true;
    

    【讨论】:

      【解决方案3】:

      else if 语句中的变量“weapon”和“solved”只需要使用 1 个'='。 像这样:

      weapon = "knife";
      solved = true;
      

      仅使用 1 个“=”将变量(武器)设置为新值(刀)。 使用 3 '===' 是在询问 this 是否等于 that 的值和类型。换句话说,您正在做的是询问“武器”是否与“刀”匹配,这将输出“假”。 === 表示专门匹配 TYPE 和 VALUE,而不仅仅是值。而 == 只会比较值,所以 "1" == 1 会输出 'true' 因为 javascript 只比较值,即使一个是字符串而一个是数字。但是 === 比较值和类型,所以 "1" === 1 会输出 'false',因为即使值相同,类型也不同(一个是字符串,一个是数字)

      请参阅 Udacity/Grow With Google 第 11.19 课 - 平等。

      【讨论】: