简体   繁体   English

用+将字符串转换为数字

[英]Convert a string to number with +

Here's an easy one for you true believers: You can use + to convert a string to a number, 这是真正的信徒的简单选择:您可以使用+将字符串转换为数字,

var thing = "12"
alert(thing);
alert(typeof thing); // string
thing = +thing;
alert(typeof thing); // number
if (thing == 112) alert("!"); // number

Can someone explain: 有人可以解释:

  1. What is the name of this process? 此过程的名称是什么?
  2. How does + convert a string to a number? +如何将字符串转换为数字?

Javascript uses a dynamic type system. Javascript使用动态类型系统。 For me it's a 'cast' operation. 对我来说,这是一个“铸造”操作。

The operator + could be a String operator ('a' + 'b') or an Number operator (1+2). 运算符+可以是字符串运算符('a'+'b')或数字运算符(1 + 2)。 It could be used also between Strings and numbers (remembering that 0 + '12' = 12 and '0'+'12' = '012') 它也可以在字符串和数字之间使用(记住0 +'12'= 12和'0'+'12'='012')

By default, i think that the JS interpreter considered +thing as 0 + things so it casts this variable to a number 默认情况下,我认为JS解释器将+ thing视为0 +事物,因此它将此变量转换为数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM