仅使用 var 在 JavaScript 中声明布尔值

2022-01-19 00:00:00 boolean javascript

如果我像这样声明一个 JavaScript 布尔变量:

If I declare a JavaScript boolean variable like this:

var IsLoggedIn;

然后用 true1 初始化它,这样安全吗?还是用 1 初始化它会使变量变成一个数字?

And then initialize it with either true or 1, is that safe? Or will initializing it with 1 make the variable a number?

推荐答案

类型取决于你的初始化:

Types are dependent to your initialization:

var IsLoggedIn1 = "true"; //string
var IsLoggedIn2 = 1; //integer
var IsLoggedIn3 = true; //bool

但是看看这个例子:

var IsLoggedIn1 = "true"; //string
IsLoggedIn1 = true; //now your variable is a boolean

您的变量类型取决于 JavaScript 中的赋值.

Your variables' type depends on the assigned value in JavaScript.

相关文章