3 回答

TA贡献1803条经验 获得超6个赞
和
var x=1
x
开始是真实的。这意味着第一个if
已完成:
if(x){x=0;}
制作x
falsey (0),所以第二个if
不运行
if(x){
所以,最后x
是0
。

TA贡献1852条经验 获得超1个赞
所以这是我对解释我所理解的内容的看法。这里我们将值 1 赋给变量 x。
var x=1
接下来,我们正在检查 x 的值。
if(x)
{
x=0;
}
if(x)如果变量 x 是其中之一,则这里的条件将被断言为真:
分配和初始化
不为空
不是未定义
不是空的
大于 0
是一个数字
真的
所以 x=1,因此,它将值 0 分配给 x。现在在下一个条件中,x 将等于 0。因此,该条件不会被断言为真。并且 x 不会被赋值为 1。因此,你得到的警报为 0。我希望它是有道理的。

TA贡献1936条经验 获得超6个赞
您正在寻找的是 Javascript 中的“强制”。当我们在需要其他类型变量的地方/函数/条件等中使用一种类型的 Javascript 变量时,Javascript 不会抛出错误。相反,它将该变量的值更改为该特定类型的变量。这叫胁迫。
例如:
var a = "" ;
if (a){ //a is coerced to false
console.log (true);
}
else{
console.log (false);
}
在上面的代码中,空字符串被强制为false。
同样,在您的代码中,正在发生强制:
var x=1
if(x){ // x is coerced to true, this condition is met and x is set to 0.
x=0;
}
if(x){ // since x is 0, it is coerced to false, so condition is not satisfied
x=1
};
alert(x);
有关更多详细信息,请查看此链接。
添加回答
举报