gpt4 book ai didi

javascript - javascript 中 2 个数字相加不正确

转载 作者:行者123 更新时间:2023-11-28 11:17:21 25 4
gpt4 key购买 nike

我的 html 中有一个下拉列表,其中的值显示在此处,

<select id="thedropdown">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>

还有我的 JavaScript:

function myFunction()
{
var a = document.getElementById("thedropdown");
var b = a.options[a.selectedIndex].value;

var y=b;
var x=y+2;
var demoP=document.getElementById("demo")
demoP.innerHTML= x;
}

然而,当我点击按钮时,答案却变成了 22,而它应该是 4。你可以看到我的问题。提前欢呼寻求帮助

最佳答案

现在您的代码连接字符串。您需要parseInt()parseFloat() (或 Number()+ )添加之前的值。

使用parseInt()时,请确保always specify the second argument (the radix) :

b = parseInt(a.options[a.selectedIndex].value, 10);

关于javascript - javascript 中 2 个数字相加不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com