我有下面的字符串

var a = "1,2,3,4";

当我…

var b = a.split(',');

我得到b为["1","2","3","4"]

我能做点什么让b等于[1,2,3,4]吗?


当前回答

由于所有的答案都允许包含NaN,所以我想补充一句,如果您想快速地将一个混合值的数组转换为数字,您可以这样做。

var a = "1,2,3,4,foo,bar";

var b = a.split(',');

var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.

// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.

其他回答

你可以使用数组。映射将每个元素转换为一个数字。

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});

检查文档


或者像User: thg435所指出的那样更优雅

var b = a.split(',').map(Number);

Number()将完成其余的工作:检查这里


注意:对于不支持map的旧浏览器,你可以自己添加一个实现:

Array.prototype.map = Array.prototype.map || function(_x) {
    for(var o=[], i=0; i<this.length; i++) { 
        o[i] = _x(this[i]); 
    }
    return o;
};

你可以在一行中将字符串数组转换为数字数组:

const arrayOfNumbers = arrayOfStrings.map(e => +e);

由于所有的答案都允许包含NaN,所以我想补充一句,如果您想快速地将一个混合值的数组转换为数字,您可以这样做。

var a = "1,2,3,4,foo,bar";

var b = a.split(',');

var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.

// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.

您可以使用JSON。解析,添加括号格式化数组

常量 a = “1,2,3,4”; const myArray = JSON.parse('[${a}]') console.log(myArray) console.info('pos 2 = ', myArray[2])

使用Array.from,试试这个:

Let b = ["1", "2", "3", "4"]; b = Array.from(b,Number); console.log (b);