2015-08-09 25 views
0

有人可以請告知爲什麼下面的函數中的'inputValue'變量沒有被轉換爲數字。我期待第二個console.log報告該變量現在是一個數字(因爲我申請parseInt它)。 但顯然它仍然是一個字符串。將字符串轉換爲JS中的數字

function checkIfNum(){ 
    var inputValue = document.getElementsByTagName('input')[0].value; 
    console.log(inputValue); 

    // Convert to a number 
    parseInt(inputValue); 

    console.log(typeof(inputValue)); 
} 

回答

3

您還沒有與結果parseInt所以因爲它的立場,你就inputValue原始值是一個字符串做typeof做任何事情。的parseInt結果分配給inputValue和你的代碼將正常工作:

function checkIfNum(){ 
    var inputValue = document.getElementsByTagName('input')[0].value; 
    console.log(inputValue); 

    // Assign the result of parseInt 
    inputValue = parseInt(inputValue, 10); 

    console.log(typeof(inputValue)); 
} 

JsFiddle(堆棧片段似乎已關閉)。

爲了確保它在一些舊版本的瀏覽器上被解析爲十進制數,我在你的parseInt調用中添加了一個基數也是毫無價值的。

+0

感謝RGraham - 有一天我會得到一個程序員的大腦。 – swisstony

+0

@swisstony嘿,我們都會犯錯!其他人更容易看到代碼中的問題,而不是看到你自己的:) – CodingIntrigue

1

因爲您沒有將parseInt的結果分配給任何東西,特別是不會將其分配給inputValue。要糾正:

inputValue = parseInt(inputValue); 
0

必須返回值從parseInt(inputValue)存儲爲一個新的變量或替換原有

function checkIfNum(){ 
var inputValue = document.getElementsByTagName('input')[0].value; 
console.log(inputValue); 

// Convert to a number 
var newInputValue = parseInt(inputValue); 

console.log(typeof(newInputValue)); 
}