是否可以声明一个变量';在JavaScript中初始化数据类型之前

是否可以声明一个变量';在JavaScript中初始化数据类型之前,javascript,Javascript,截至2017年10月11日,声明如下: JavaScript是一种松散类型或动态语言。这意味着您不必提前声明变量的类型。处理程序时,类型将自动确定 这意味着,除其他外,我们可以编写更少的代码,因为JS会在初始化变量时自动检测数据类型。例如: let amount = 0; // since 0 is a number, this variable is of type "number" amount += 1; // which makes it real easy to add anoth

截至2017年10月11日,声明如下:

JavaScript是一种松散类型或动态语言。这意味着您不必提前声明变量的类型。处理程序时,类型将自动确定

这意味着,除其他外,我们可以编写更少的代码,因为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
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
不过,在做了一些研究之后,我认为将第二句改为:

这意味着您不能提前声明变量的类型

例如:

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
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);

一些项目喜欢并将静态类型检查引入Javascript。

Javascript中的变量没有类型。值具有类型,并且可以为变量分配任何类型的值,而不管其当前值的类型如何。即使JS是静态类型的,也不一定意味着存在默认初始化。你面临的实际问题是什么?@llama,主要是好奇。文档暗示我们有选择的余地。@samurai_jane我对MDN文档做了一些编辑,因为它显然具有误导性。不幸的是,MDN上的许多教程类型的文档都有类似的有问题的内容,就像我喜欢MDN一样。