【问题标题】:Why can I multiple and subtract a string and a number为什么我可以乘以和减去一个字符串和一个数字
【发布时间】:2014-07-30 09:37:21
【问题描述】:

为什么在 JavaScript 中我可以使用数字字符串执行诸如乘法和减法之类的运算。 “10”带数字?

JavaScript 是否进行类型推断?

考虑下面的例子,为什么在最后两个语句中我得到 1010 而不是 20?

var foo = "Hello, world!";
var bar = "10";



var x = foo * 10; // x is now bound to type number
console.log("type of x= " + typeof x + ", value of x= " +  x); // this will print number NaN, that makes sense..


var y = bar * 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 100

y = bar - 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 0 

y = bar + 10; // y is now bound to type string!!
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 1010

y = eval(bar + 10); // y is now bound to type number!!!! 
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 1010 

日志输出:

type of x= number, value of x= NaN
type of y= number, value of y= 100
type of y= number, value of y= 0
type of y= string, value of y= 1010
type of y= number, value of y= 1010

【问题讨论】:

  • 加号既用于字符串连接,也用于添加数字,因此当其中一个值是字符串时,另一个值也被合并为字符串。您不能对字符串进行乘法运算或减法运算,因此当使用这些运算符时,这些值会与数字相一致。
  • 在这里找到好的解决方案:stackoverflow.com/questions/7124884/…

标签: javascript types type-conversion


【解决方案1】:

在第二个例子中

var y = bar * 10

Javascript 假设您要执行数学运算并将原始字符串强制转换为数字。

在最后两个示例中,您尝试将 10(数字)添加到 bar。 bar(你的变量)是一个字符串,所以 JavaScript 会尽力而为,假设你想要一个字符串作为结果,并通过连接“10”(作为一个字符串)来创建一个字符串,并且不会将你的原始字符串强制转换为一个数字。

类型强制的规则很复杂。我会尝试为您找到一个链接。但是 Douglas Crockford 的“JavaScript: The Good Parts”是一本不错的读物。

编辑

试试这个,很好地解释了这一切。

http://united-coders.com/matthias-reuter/all-about-types-part-2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2010-10-06
    • 2014-03-04
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多