繁体   English   中英

在JS中将字符串转换为数字

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM