JavaScript 字符串赋值运算符
为什么我可以在字符串上使用 +=
,但不能在字符串上使用 -=
?
例如...
var test = "Test";
var arr = "⇔"
test += arr;
alert(test); // Shows "Test⇔"
test -= arr;
alert(test); // Shows "NaN"
How come I can use +=
on a string, but I cannot use -=
on it?
For example...
var test = "Test";
var arr = "⇔"
test += arr;
alert(test); // Shows "Test⇔"
test -= arr;
alert(test); // Shows "NaN"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
简短的答案是 - 它没有被定义为与字符串一起使用。
更长的答案:如果您尝试对两个字符串进行减法运算符,它会首先将它们转换为数字,然后执行算术运算。
如果您尝试非数字的内容,您会收到 NaN 相关错误:
The short answer is - it isn't defined to work with strings.
Longer answer: if you try the subtraction operator on two strings, it will first cast them to numbers and then perform the arithmetic.
If you try something that is non-numeric, you get a NaN related error:
因为
+
运算符连接字符串,而-
运算符仅将数字相减。至于为什么——可能是因为很难确定人们在字符串相减时想要做什么。
例如:
这应该做什么?
Because the
+
operator concatenates strings, but the-
operator only subtracts numbers from each other.As to the why -- probably because it is difficult to determine what people want to do when they subtract strings from each other.
For example:
What should this do?
如上所述,
-=
运算符未重载以用于字符串,它仅适用于数字。如果您尝试将其与字符串一起使用,则该运算符将尝试将两个操作数转换为
Number
,这就是您得到NaN
的原因,因为:要摆脱 <
test
字符串上的 code>arr 内容,您可以 替换它:As all said, the
-=
operator is not overloaded to work with Strings, it only works with Numbers.If you try to use it with strings, the operator will try to convert both operands to
Number
, that is why you are gettingNaN
, because:To get rid of the
arr
content on yourtest
string, you can replace it:这是因为减号不是有效的字符串运算符,而加号被重载以处理数字(加法运算符)和字符串(连接运算符)。
您希望从中得到什么结果?
That's because the minus sign is not a valid String operator, whereas the plus sign is overloaded to handle both Numbers (addition operator) and Strings (concatenation operator).
What results were you hoping to get from this?
通常,编程语言不定义字符串减法。 += 首先并不是真正的加法,而是连接。
Generally, programming languages don't define subtraction for strings. += isn't really addition in the first place, it's concatenation.
因为+(加号)也是字符串连接运算符,而-(减号)仅适用于减法。如果 JavaScript 可以将 2 个字符串附加在一起,它不会抱怨,但如果你尝试减去 2 个字符串,它就没有任何意义。
Because the +(plus sign) is also the string concatenation operator, while the -(minus sign) only applies to subtraction. If JavaScript can append 2 strings together it won't complain, but if you try to subtract 2 strings, it just doesn't make any sense.