javascript 如何在javascript中使用类型变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9659753/
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
How to use typed variables in javascript?
提问by errgod
Is there any way to use typed variables in javascript? Like integer, string, float...
有没有办法在javascript中使用类型化变量?像整数,字符串,浮点数...
回答by John Pick
JavaScript variables are not typed.
JavaScript 变量没有类型化。
JavaScript values are, though. The same variable can change (be assigned a new value), for example, from uninitialized to number to boolean to string (not that you'd want to do this!):
但是,JavaScript 值是。相同的变量可以改变(被分配一个新值),例如,从未初始化到数字到布尔值到字符串(不是你想要这样做!):
var x; // undefined
x = 0; // number
x = true; // boolean
x = "hello"; // string
回答by Peter Olson
Javascript is dynamically typed, whereas other languages, C# and Java for example, are statically typed. This means that in Javascript variables can be reassigned to values of any type, and thus that you don't ever need to explicitly denote the type of variables or the return type of functions. If you saw code like this in a statically typed language
Javascript 是动态类型的,而其他语言,例如 C# 和 Java,是静态类型的。这意味着在 Javascript 中变量可以重新分配给任何类型的值,因此您永远不需要明确表示变量的类型或函数的返回类型。如果你在静态类型语言中看到这样的代码
int x = 5;
x = "hello";
you would rightfully expect the compiler to start throwing up a big nasty TypeError
. Javascript, on the other hand, will happily run this code even though the type changed.
你理所当然地期望编译器开始抛出一个很大的令人讨厌的TypeError
. 另一方面,即使类型改变了,Javascript 也会愉快地运行这段代码。
var x = 5;
x = "hello";
Because variables can change types, the compiler can't know as much information about them. You should expect the tools for Javascript to be inferior to those of Java/C# as far as useful niceties like code completion go. Fewer mistakes will be caught at compile time and you will have to do more runtime debugging than you are probably used to.
因为变量可以改变类型,所以编译器不能知道关于它们的太多信息。就代码完成等有用的细节而言,您应该期望 Javascript 工具不如 Java/C# 工具。在编译时捕获的错误更少,您将不得不进行比您习惯的更多的运行时调试。
That said, this also allows you to be more free with your variables and you can change types at will, which can often be convenient. You can write code like this if you want:
也就是说,这也使您可以更自由地使用变量,并且可以随意更改类型,这通常很方便。如果你愿意,你可以写这样的代码:
var x; //typeof x === "undefined"
x = "Hello, world!"; //typeof x === "string"
x = 42; //typeof x === "number"
x = false; //typeof x === "boolean"
x = {}; //typeof x === "object"
回答by Chris
Not possible in Javascript, but if you really need it, you should check TypeScript. It is a superset of Javascript that adds optional static typing. It also has class-based programming.
在 Javascript 中不可能,但如果你真的需要它,你应该检查 TypeScript。它是 Javascript 的超集,添加了可选的静态类型。它还具有基于类的编程。
回答by FloatOverflow
People writing "why shouldn't use it / you shouldn't use it" are wrong. In the next Java Script 2.x specification there is a plan to add strong typed variables.
写“为什么不应该使用它/你不应该使用它”的人是错误的。在下一个 Java Script 2.x 规范中,计划添加强类型变量。
Meanwhile you may use very simple solution to emulate strong types:
同时,您可以使用非常简单的解决方案来模拟强类型:
var = Object.create( String );
After that autocompleting in a lot of IDE (including IntelliJ IDEA) will work great and you have declared and initialized an object of specified type.
之后,在许多 IDE(包括 IntelliJ IDEA)中自动完成会很好用,并且您已经声明并初始化了一个指定类型的对象。
Read more on my blog.
在我的博客上阅读更多内容。
回答by M81
There is a simple hack to simulate typed variables in Javascript using typed arrays.
有一个简单的技巧可以使用类型化数组在 Javascript 中模拟类型化变量。
var a = new Int8Array(1);
a[0]=5;
a[0]=~a[0]; // -6
var b = new Uint8Array(1);
b[0]=5;
b[0]=~b[0]; // 250
The only useful reason I know for ever doing this is when you need to use bitwise operations on an unsigned integer when translating code from a typed language which has to do exactly the same in Javascript. Javascript integers are signed by default and bitwise operations can mess up the sign.
我知道永远这样做的唯一有用的原因是当您需要在从类型语言翻译代码时对无符号整数使用按位运算时,该语言必须在 Javascript 中执行完全相同的操作。默认情况下,Javascript 整数是有符号的,按位运算可能会弄乱符号。
Creating a typed array for just a single variable is generally not good for the performance.
仅为单个变量创建类型化数组通常对性能不利。
Often...
经常...
var b=5;
b=(~b)&0xff; // 250
will do the trick just fine and only 32-bit unsigned integers need to be typed in Javascript to avoid problems with bitwise operations.
会很好地完成这个技巧,并且只需要在 Javascript 中输入 32 位无符号整数,以避免按位运算出现问题。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays#Typed_array_views
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays#Typed_array_views
回答by Andrei
One of the main characteristics of Javascript is that it is weak typed language. Why do you need strong types anyways?
Javascript 的主要特征之一是它是弱类型语言。为什么你需要强类型?
回答by clagccs
I recommend you read this:
我建议你阅读这个:
http://en.wikipedia.org/wiki/Strong_typing
http://en.wikipedia.org/wiki/Strong_typing
javascript is a weak and dynamic type..it's dynamic because the variable type is determine in the runtime, and is loosely type because you can perform this operation for example
javascript 是一种弱动态类型..它是动态的,因为变量类型是在运行时确定的,并且是松散的类型,因为您可以执行此操作,例如
var letter = "2";
var number = 2;
console.log(letter+number);
this in java, c# or any other static and stricted type language will make an error but in javascript you get a "22" as result (it is because javascript is weak typed or loosely typed)
这在 java、c# 或任何其他静态和严格类型语言中都会出错,但在 javascript 中,结果是“22”(这是因为 javascript 是弱类型或松散类型)
now..you've other languages than keep use typed values, like clojure or dart, where for performance reasons, you can use functions or methods with typed arguments, javascript doesn't let this and only accept dynamic values, like ruby...
现在..你有其他语言而不是继续使用类型化值,比如 clojure 或 dart,出于性能原因,你可以使用带有类型化参数的函数或方法,javascript 不允许这样做,只接受动态值,比如 ruby .. .
I hope this help and you can understand my poor english :D
我希望这会有所帮助,您可以理解我糟糕的英语:D
回答by Kenneth Funk
Javascript is a loosely typed language, so no, there aren't types as you are used to in some other languages.
Javascript 是一种松散类型的语言,所以不,没有您在其他一些语言中习惯的类型。
回答by Valery Rode
<html>
<head>
<meta charset="utf-8">
<title>JS_Byte</title>
<script>
class Byte
{
constructor(Value)
{
this.Number = new Uint8Array(1);
this.Number[0] = Value;
}
get Get()
{
return this.Number[0];
}
set Set(newValue)
{
this.Number[0] = newValue;
}
};
//On load
function Load_Page()
{
let Byte_Num = new Byte(12);
document.write(Byte_Num.Get.toString() + "<br>");// -> 12
Byte_Num.Set = 14;
document.write(Byte_Num.Get.toString() + "<br>");// -> 14
Byte_Num.Set = 256;
document.write(Byte_Num.Get.toString() + "<br>");// -> 0
}
</script>
</head>
<body onload="Load_Page()">
</body>
回答by Hossein Aghatabar
you can use TypeScriptfor definition types for values
您可以使用TypeScript来定义值的类型