[英]Converting a String to a Number in JS
有人可以告訴我為什么下面函數中的'inputValue'變量沒有被轉換成數字嗎? 我期望第二個console.log
報告該變量現在是一個數字(因為我對其應用了parseInt
)。 但是顯然它仍然是一個字符串。
function checkIfNum(){
var inputValue = document.getElementsByTagName('input')[0].value;
console.log(inputValue);
// Convert to a number
parseInt(inputValue);
console.log(typeof(inputValue));
}
您實際上沒有對parseInt
的結果做任何事情,因此,您正在對inputValue
的原始值(字符串)進行typeof
inputValue
。 將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
調用中添加一個基數以確保在某些較舊的瀏覽器中將其解析為十進制值也一文不值。
因為您沒有將parseInt
的結果分配給任何東西,尤其是沒有分配給inputValue
。 糾正:
inputValue = parseInt(inputValue);
您必須將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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.