admin管理员组文章数量:1279214
This is purely an educational question.
I'm working on a new version of a web app that the pany I'm working for had made earlier. when re-writing the math, I came across this:
document.getElementById("estResidual").value-0;
Thinking there was no purpose for the "-0", I removed it. But when I tried the calculations, the numbers were waaayyyyyy off. Then I tried re-adding the "-0", and voila! everything worked nicely.
The Question: What did the "-0" do to change the value?
This is purely an educational question.
I'm working on a new version of a web app that the pany I'm working for had made earlier. when re-writing the math, I came across this:
document.getElementById("estResidual").value-0;
Thinking there was no purpose for the "-0", I removed it. But when I tried the calculations, the numbers were waaayyyyyy off. Then I tried re-adding the "-0", and voila! everything worked nicely.
The Question: What did the "-0" do to change the value?
Share Improve this question asked Mar 4, 2014 at 20:22 DanTheManDanTheMan 5562 gold badges7 silver badges21 bronze badges 2-
1
Note - when you use
+ 0
it might still look like a concatenation. There is no confusion with the minus. – Floris Commented Mar 4, 2014 at 20:24 - 1 @Floris - just re-read your ment and realized that too... so I deleted mine. :) – Steve Commented Mar 4, 2014 at 20:34
3 Answers
Reset to default 19It's an (ab)use of JavaScript's soft typing behavior. In this case, it will convert a string to a float:
> "13"
"13"
> "13"-0
13
> "1.01"-0
1.01
Unary +
will do the same:
> +"13"
13
> +"9.9"
9.9
Note that using +
will instead convert the integer 0
into a string and concatenate it:
> "13"+0
"130"
This is all standardized. For explicit details on how these operators should behave, you can always check the ECMAScript Language Specification (e.g. addition, subtraction. unary plus).
The JS engine re-casts on the fly to try and make statements work. So JS will cast "23" to an integer 23
when you try to perform math on it, and likewise it will convert integer 23
to string "23" if you do something like:
var a = 23;
console.log(23 + "asdf");
//outputs "23asdf"
That forces the type of object to bee a number rather than a string.
本文标签: Javascript what is quot 0quot doingStack Overflow
版权声明:本文标题:Javascript: what is "- 0" doing? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741277976a2369840.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论