html - Why is "5" + 2+3 and 2+3+ "5" different in JavaScript? - Stack Overflow

Why is "5" + 2+3 and 2+3+ "5" different in JavaScript?This if giving me wrong resul

Why is "5" + 2+3 and 2+3+ "5" different in JavaScript?

This if giving me wrong result.

<p>The result of adding "5" + 2 + 3</p>

<p id="demo"></p>

<script>
  x = "5" + 2 + 3;
  document.getElementById("demo").innerHTML = x;
</script>

<p> result of adding 2+3+"5"</p>
<p id="qwe"></p>
<script>
  y = 2 + 3 + "5";
  document.getElementById("qwe").innerHTML = y;
</script>

Why is "5" + 2+3 and 2+3+ "5" different in JavaScript?

This if giving me wrong result.

<p>The result of adding "5" + 2 + 3</p>

<p id="demo"></p>

<script>
  x = "5" + 2 + 3;
  document.getElementById("demo").innerHTML = x;
</script>

<p> result of adding 2+3+"5"</p>
<p id="qwe"></p>
<script>
  y = 2 + 3 + "5";
  document.getElementById("qwe").innerHTML = y;
</script>

Share Improve this question edited Apr 22, 2020 at 12:34 Ivar 6,86712 gold badges56 silver badges67 bronze badges asked Apr 22, 2020 at 12:26 jigyasajigyasa 211 silver badge3 bronze badges 2
  • 2 What's the right result? What were you expecting? – Rup Commented Apr 22, 2020 at 12:29
  • Does this answer your question? How does adding String with Integer work in JavaScript? – kevinSpaceyIsKeyserSöze Commented Apr 22, 2020 at 12:36
Add a ment  | 

1 Answer 1

Reset to default 9

+ evaluates left-to-right, so

"5" + 2+3

is equivalent to

("5" + 2) + 3

and the other one:

2+3+ "5"

is equivalent to:

(2 + 3) + "5"

When two numbers are +d together, they are added, so the result is a number. But if either side of the + is a string, the two expressions are concatenated instead of added. So

("5" + 2) + 3
// results in
'52' + 3
'523'
(2 + 3) + "5"
// results in
5 + '5'
55

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742333787a4424243.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信