MDN's documentation截至 2017 年 10 月 11 日,声明如下:
JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed.
这意味着我们可以编写更少的代码,因为 JS 在初始化变量时会自动检测数据类型。例如:
let amount = 0; // since 0 is a number, this variable is of type "number"
amount += 1; // which makes it real easy to add another number to it
console.log(amount); // returns 1
但是,经过一些研究后,我认为将第二句修改为:
That means you cannot declare the type of variable ahead of time.
例如:
let amount; // without initialization, this variable is of type "undefined"
amount += 1; // which makes it impossible to add a number to it
console.log(amount); // returns NaN
如果有一种方法可以在初始化变量之前声明变量的数据类型,请在您的答案中提供详细信息。
最佳答案
不可能在普通的 Javascript 中声明变量的类型,即使在最新的规范(ES7)中也是如此。也没有静态类型检查。
您在此处观察到的行为:
let amount;
amount += 1;
console.log(amount);
...是由于 undefined + 1
计算结果为 NaN
,这可能有意义也可能没有意义,但这就是 JS 的工作方式。
您可以重新分配任何类型的变量:
let a = 1;
a = 'asdf';
console.log(b);
一些项目,如 Flow和 Typescript为 Javascript 带来静态类型检查。
关于javascript - 在 JavaScript 中初始化变量之前是否可以声明变量的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46699373/