当使用b / w两个字符串时,' - '(减号)将如何在Javascript中工作? [英] How will ' - '(minus) will work in Javascript when used b/w two strings?
问题描述
<script language="javascript" type="text/javascript">
var num1="5";
var num2="3";
var sum=num1-num2;
document.write("The sum is:" +sum);
</script>
加成将给出53作为O / p好。
减法给出2作为o / p。为什么产生这个o / p.
想知道原因。
Addition will give 53 as O/p alright.
subtraction is giving 2 as o/p.Why this o/p is produced.
Want know the reason for that.
推荐答案
Javascript是一种弱类型的语言,意味着它会尝试为你转换数据。
它特别有一个字符串连接运算符:'+'
所以当它解析你的代码并看到这个:
Javascript is a weakly typed language, which means it tries to convert data for you when it can.
And it specifically has a string concatenation operator: '+'
So when it parses your code and sees this:
var num1="5";
var num2="3";
var sum=num1+num2;
它查看您给出的实际数据类型,因为其中至少有一个是一个字符串,它决定使用字符串连接运算符并组合字符串 - 所以你得到一个字符串结果53
但是...没有什么明智的可以从字符串中减去 - 所以没有字符串去连接运算符。所以遇到这个时:
It looks at the actual datatypes you have given it and because at least one of them is a string it decides to use the string concatenation operator and combines the strings - so you get a string result "53"
But...there is nothing sensible that can be subtracted from strings - so there is no "string deconcatenation" operator. So when it encounters this:
var num1="5";
var num2="3";
var sum=num1-num2;
它必须使用减法运算符,并将每个strign首先转换为数字 - 所以你得到5 - 3,或2
it has to use the subtract operator, and converts each strign to a number first - so you get 5 - 3, or 2
这篇关于当使用b / w两个字符串时,' - '(减号)将如何在Javascript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!