2015-08-09 22 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)); 
}