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


当前回答

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

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

其他回答

尝试str-0将字符串转换为数字。

> str = '0'
> str - 0
  0
> str = '123'
> str - 0
  123
> str = '-12'
> str - 0
  -12
> str = 'asdf'
> str - 0
  NaN
> str = '12.34'
> str - 0
  12.34

以下是两个链接,用于比较将字符串转换为int的几种方法的性能

https://jsperf.com/number-vs-parseint-vs-plus

http://phrogz.net/js/string_to_number.html

function parseIntSmarter(str) {
    // ParseInt is bad because it returns 22 for "22thisendsintext"
    // Number() is returns NaN if it ends in non-numbers, but it returns 0 for empty or whitespace strings.
    return isNaN(Number(str)) ? NaN : parseInt(str, 10);
}

我用这个

String.prototype.toInt = function (returnval) {
    var i = parseInt(this);
     return isNaN(i) ? returnval !== undefined ? returnval : - 1  :      i;
}

var str = "7";
var num = str.toInt(); // outputs 7, if not str outputs -1
//or
var num = str.toInt(0); // outputs 7, if not str outputs 0

这样我总能得到一个整数。

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

即: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;
}

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

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