javascript - 在 JavaScript 中初始化变量之前是否可以声明变量的数据类型

标签 javascript

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

一些项目,如 FlowTypescript为 Javascript 带来静态类型检查。

关于javascript - 在 JavaScript 中初始化变量之前是否可以声明变量的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46699373/

相关文章:

javascript - Angular2 如何使用 Javascript XMLHttpRequest 重定向到另一个组件?

php - 打开 URL 时页面继续加载

javascript - OpenLayers map 未正确加载

javascript - 同时在 Highcharts 中显示多个工具提示

javascript - 为什么 styled-jsx 标签中的变量不起作用?

javascript - Python Unix 时间在 Javascript 中不起作用

javascript - 当我更改 Three.js 网格的比例时,为什么我的旋转会出错?

javascript - 引用错误 : $traceurRuntime is not defined (in angularjs app)

javascript - 无法重绘以 base64 表示的图像

javascript - 提交表单时添加CSS javascript