将 javascript 变量声明为特定类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14202743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:00:47  来源:igfitidea点击:

Declaring javascript variables as specific types

javascriptvariablesvariable-declaration

提问by CBredlow

The title says it all, but I will provide more clarification:

标题说明了一切,但我将提供更多说明:

After seeing many samples of javascript where all variables are declared as type var, and seeing support for other datatypes, why aren't variables of a specific datatype declared as such? Meaning, why isn't this:

在看到所有变量都声明为 type 的许多javascript示例var并看到对其他数据类型的支持后,为什么不这样声明特定数据类型的变量?意思是,为什么不是这个:

string hello = 'Hello, World'

string hello = 'Hello, World'

used instead of

代替

var hello = 'Hello, World'

var hello = 'Hello, World'

Looking at sites like OReilly Javascriptshows that there are reserved words for other types. Again, why aren't they used? Wouldn't it make lines like this: typeof(variable)==='string';no longer needed?

看看像OReilly Javascript这样的网站,就会发现其他类型的保留字。再次,为什么不使用它们?会不会像这样:typeof(variable)==='string';不再需要?

回答by Matt Ball

Quite simply, JavaScript variables do not have types. The valueshave types.

很简单,JavaScript 变量没有类型。该具有的类型。

The language permits us to write code like this:

该语言允许我们编写如下代码:

var foo = 42;
foo = 'the answer';
foo = function () {};

So it would be pointless to specify the type in a variable declaration, because the type is dictated by the variable's value. This fairly common in "dynamic" languages.

所以在变量声明中指定类型是没有意义的,因为类型是由变量的值决定的。这在“动态”语言中相当普遍。