JavaScript中的自动类型转换 [英] Auto-type conversion in JavaScript

查看:29
本文介绍了JavaScript中的自动类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中的以下所有表达式都是显而易见的.

The following all expressions in JavaScript are far obvious.

var x = 10 + 10;

x 的值是 20 .

x = 10 + '10';

在这种情况下, x 的值为 1010 ,因为 + 运算符已重载.如果任何一个操作数的类型为string,则进行字符串串联;如果所有操作数均为数字,则执行加法运算.

The value of x in this case is 1010 because the + operator is overloaded. If any of the operands is of type string, string concatenation is made and if all the operands are numbers, addition is performed.

x = 10 - 10;
x = 10 - '10';

在这两种情况下, x 的值都将为 0 ,因为-运算符不会以这种方式重载并且所有操作数如果不是在执行实际减法之前没有将它们转换为数字(如果我仍然错了,您可以澄清一下).

In both of these cases, the value of x will be 0 because the - operator is not overloaded in that way and all operands are converted to numbers, if they are not before the actual subtraction is performed (you may clarify, if anyway I'm wrong).

以下表达式中会发生什么.

What happens in the following expression.

x = '100' - -'150';    

x 的值是 250 .这似乎也很明显,但是该表达式在某种程度上似乎等效于以下表达式.

The value of x is 250. Which also appears to be obvious but this expression somewhat appears to be the equivalent to the following expression.

x = '100' +'150';

如果是这种情况,则将这两个字符串连接起来并为 x 分配了 100150 .那么为什么要在这种情况下执行加法运算呢?

If it had been the case then these two strings would have been concatenated and assigned 100150 to x. So why is addition performed in this case?

+'10'+ 5 返回 15 ,而'a'+ +'b'返回 aNaN .有人知道为什么吗?

+'10' + 5 returns 15 and 'a' + + 'b' returns aNaN. Does anyone know why?

推荐答案

在您的情况下,不会先评估--使其等同于 + .-"150" 被评估为数字,因此成为 -150 .

In your case - - is not evaluated first to become equivalent to +. -"150" is evaluated as a number, and so became -150.

由于您无法减去字符串( NaN ),因此JS然后采用"100" 并生成一个数字,然后运行 100 - -150 ,即250.

As you can't subtract a string (NaN), JS then take "100" and make a number, and then it run 100 - -150 which is 250.

关键是您实际上不能减去类型字符串,因此它将这些字符串转换为数字.

The key is really that you can't subtract type string, so it converts those strings to numbers.

这篇关于JavaScript中的自动类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆