将声明的null变量更新为布尔值

Updating the Declared null variable to Boolean

本文关键字:更新 布尔值 变量 null 声明      更新时间:2023-09-26

在JavaScript的其他函数中声明null变量并将其更新为布尔值是正确的吗?

var isAnswerd = null;
if(condition){ isAnswerd = true;}
if(another condition){ isAnswerd = false;}

我知道我可以在一开始就声明变量为真或假但在这里我不需要这样做

Javascript有'动态类型'

与c#等强类型语言不同,您可以更容易地将变量赋值为任何类型。

例如:

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

来源:http://www.w3schools.com/js/js_datatypes.asp

根据javascript的工作方式,你不需要预先初始化变量。

你能做的是

if(condition){ isAnswerd = true;}
if(another condition){ isAnswerd = false;}

和最后

if(typeof(isAnswered) != "undefined"){
.. 
}

if(condition){ isAnswerd = true;}
if(typeof(isAnswered) != "undefined"){
.. 
}
else{
..
}

在第二个例子中,您没有为false条件声明变量