[英]Javascript += equivalent?
我的代碼是一個簡單的函數,它檢查按下了哪個單選按鈕,並將該單選按鈕的值添加到我的var input = 0;
。 但是,我知道我做錯了,因為它有效,但輸出錯誤。 當其中一個if
語句為真時,而不是輸入(0)現在等於它本身加上getElementById("small").value
,它打印出010
而不是現在的10
。
我知道在Java中有一個類似於input += getElementById("small").value;
的約定input += getElementById("small").value;
但這似乎不起作用。 因此,正如您在下面的示例中所看到的,我嘗試了input = input + /*code*/;
的替代方法input = input + /*code*/;
但仍然沒有運氣。
我是JavaScript的新手,但對Java非常熟悉。 我想我在這里只是使用了錯誤的語法,但我所有的Google搜索都是破產。
function calculate()
{
var input = 0;
if (document.getElementById("small").checked)
{
input = input + document.getElementById("small").value;
}
else if (document.getElementById("medium").checked)
{
input = input + document.getElementById("medium").value;
}
else if (document.getElementById("large").checked)
{
input = input + document.getElementById("large").value;
}
else
{
alert("failed");
}
document.getElementById("outar").innerHTML = input;
}
你正試圖用字符串算術。 您需要在每個document.getElementById("....").value
表達式周圍使用parseInt()
,因為.value
屬性是一個字符串。
例:
input += parseInt(document.getElementById("small").value);
默認情況下,您的值不是數字,而是字符串。 你必須先解析它:
input += parseInt(document.getElementById("large").value);
您可以在字符串值之前添加額外的+符號,以便將其轉換為數字:
input += +document.getElementById("large").value;
您需要使用parseInt
或parseFloat
將.value
轉換為整數或浮點數。 .value
是一個字符串。
Javascript是動態類型語言,不像java那樣是靜態類型。 document.getElementById(“small”)。value返回一個字符串,需要使用parseInt()將其轉換為int。
何[有幫助:)
你也可以參考這個鏈接 -
值的返回值是一個字符串。 在進行任何算術運算之前,必須將其轉換為int。
JavaScript是一種動態類型語言,不像java那樣是靜態類型的。
返回值 :一個String,表示文本字段的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.