如何在JavaScript中将字符串转换为整数?


当前回答

确保获得有效整数的最安全方法:

let integer = (parseInt(value, 10) || 0);

示例:

// Example 1 - Invalid value:
let value = null;
let integer = (parseInt(value, 10) || 0);
// => integer = 0
// Example 2 - Valid value:
let value = "1230.42";
let integer = (parseInt(value, 10) || 0);
// => integer = 1230
// Example 3 - Invalid value:
let value = () => { return 412 };
let integer = (parseInt(value, 10) || 0);
// => integer = 0

其他回答

在我看来,没有答案涵盖所有边缘情况,因为解析浮点值会导致错误。

function parseInteger(value) {
    if(value === '') return NaN;
    const number = Number(value);
    return Number.isInteger(number) ? number : NaN;
}
parseInteger("4")            // 4
parseInteger("5aaa")         // NaN
parseInteger("4.33333")      // NaN
parseInteger("aaa");         // NaN

我喜欢这个把戏:

~~"2.123"; //2
~~"5"; //5

双位负数在小数点之后会丢弃任何内容,并将其转换为数字格式。我被告知它比调用函数等稍快,但我并不完全相信。

我刚才在这里看到的另一个方法(一个关于JavaScript>>>运算符的问题,它是一个零填充右移),它显示了用这个运算符将数字移位0将数字转换为uint32,如果您也希望它无符号,这是很好的。同样,这将转换为无符号整数,如果使用有符号数字,这可能会导致奇怪的行为。

"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5

将数字的乘法与各自的十次幂相加:

即:123=100+20+3=1100+2+10+31=1*(10^2)+2*(10^1)+3*(10^0)

function atoi(array) {

    // Use exp as (length - i), other option would be
    // to reverse the array.
    // Multiply a[i] * 10^(exp) and sum

    let sum = 0;

    for (let i = 0; i < array.length; i++) {
        let exp = array.length - (i+1);
        let value = array[i] * Math.pow(10, exp);
        sum += value;
    }

    return sum;
}

尝试parseInt函数:

var number = parseInt("10");

但有一个问题。如果您尝试使用parseInt函数转换“010”,它将检测为八进制数,并将返回数字8。因此,需要指定基数(从2到36)。在这种情况下,底座10。

parseInt(string, radix)

例子:

var result = parseInt("010", 10) == 10; // Returns true

var result = parseInt("010") == 10; // Returns false

请注意,parseInt在解析任何有效数据后忽略错误数据。此guid将解析为51:

var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true

我只在字符串前加了一个加号(+),这就是解决方案!

+"052254" // 52254