Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

javascript - 将两个数字相加即可将它们串联起来,而不是计算总和(Adding two numbers concatenates them instead of calculating the sum)

I am adding two numbers, but I don't get a correct value.(我将两个数字相加,但得不到正确的值。)

For example, doing 1 + 2 returns 12 and not 3(例如,做1 + 2返回12,而不是3) What am I doing wrong in this code?(我在这段代码中做错了什么?) function myFunction() { var y = document.getElementById("txt1").value; var z = document.getElementById("txt2").value; var x = y + z; document.getElementById("demo").innerHTML = x; } <p> Click the button to calculate x. <button onclick="myFunction()">Try it</button> </p> <p> Enter first number: <input type="text" id="txt1" name="text1" value="1"> Enter second number: <input type="text" id="txt2" name="text2" value="2"> </p> <p id="demo"></p>   ask by okconfused translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They are actually strings, not numbers.(它们实际上是字符串,而不是数字。)

The easiest way to produce a number from a string is to prepend it with + :(从字符串产生数字的最简单方法是在其前面加上+ :) var x = +y + +z;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...