如何将一串数字转换为数字数组?

我有下面的字符串

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

当我…

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

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

我可以做一些事情来获得b作为[1, 2, 3, 4]吗?

442144 次浏览

可以使用Array.map将每个元素转换为数字。

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

+string将尝试将字符串更改为数字。然后使用Array.map函数更改每个元素。

"1,2,3,4".split(',').map(function(el){ return +el;});

将其映射为整数:

a.split(',').map(function(i){
return parseInt(i, 10);
})

map查看每个数组项,将其传递给所提供的函数,并返回一个包含该函数返回值的数组。map在旧浏览器中不可用,但大多数库,如jQuery下划线都包含跨浏览器版本。

或者,如果你喜欢循环:

var res = a.split(",");
for (var i=0; i<res.length; i++)
{
res[i] = parseInt(res[i], 10);
}

作为一种变体,你可以使用_.map_.ary方法的组合。整个转型将更加紧凑。下面是来自官方文档的例子:

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// → [6, 8, 10]

不需要使用lambdas和/或将radix参数赋给parseInt,只需使用parseFloatNumber即可。

原因:

  1. < p >工作:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
    // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
    var i,t,m,s=n();
    for(i=0;i++<c;)t=arr.map(m);
    return n()-s
    }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    
    > f(Number)
    > 3964 // still the same
    
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    
    > f(parseFloat)
    > 3737 // all ok
    
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

一个更简短的解决方案:将参数映射并传递给Number:

.
var a = "1,2,3,4";
var b = a.split(',');
console.log(b);
var c = b.map(Number);
console.log(c);

下划线js的方式-

var a = "1,2,3,4",
b = a.split(',');


//remove falsy/empty values from array after split
b = _.compact(b);
//then Convert array of string values into Integer
b = _.map(b, Number);


console.log('Log String to Int conversion @b =', b);

由于所有的答案都允许包含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.

使用arraw函数的Matt Zeunert版本(ES6)

const nums = a.split(',').map(x => parseInt(x, 10));

Array.from()的详细信息请到中数

let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);

let c = ["1", "2", "3", "4"].map(Number);

bc是一个数字数组。

演示:

let a = "1,2,3,4";
let b = Array.from(a.split(','),Number);


let c = ["1", "2", "3", "4"].map(Number);


console.log(`b: ${b}, c: ${c}`);

这很简单。如:

["1", "2", "3", "4"].map(i=>Number(i))

你可以运行演示。

let result = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(result);

我对高尔夫球手的看法:

b="1,2,3,4".split`,`.map(x=>+x)

backquote是字符串字面值,所以我们可以省略圆括号(因为split函数的性质),但它相当于split(',')。字符串现在是一个数组,我们只需要用一个返回字符串整数的函数来映射每个值,因此x=>+x(它甚至比Number函数还要短(5个字符而不是6个字符))相当于:

function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)}         // lambda are shorter and parseInt default is 10
(x)=>{return +x}                  // diff. with parseInt in SO but + is better in this case
x=>+x                             // no multiple args, just 1 function call

我希望它能更清楚一点。

一个衬套

Array.from(a.split(','), Number)

你可以使用JSON.parse,添加括号来格式化< >强数组< / >强

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

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

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

如果您需要将字符串数组转换为数字,这将非常有效。

const numbers = arr => arr.map(Number);
numbers(['1', '2', '3','4']);     // [1, 2, 3, 4]
let ar = [ '682',    '874',    '906',    '11168',  '73714',
'74377',  '74034',  '138860', '138891', '139161', '139562',
'139733', '139560', '74049',  '139759', '139934', '140104',
'141335', '141356', '141334', '141337', '141360', '141358',
'141365', '141419', '143333', '151477', '147342', '141355',
'167847', '192141', '196760', '191687', '197351', '197055',
'198852', '198731', '198816', '199034', '200053', '199226',
'217818', '200055', '222039', '230533', '230530', '231127',
'222042', '231100', '236171', '236913', '236980', '237015',
'237016', '237052', '237551', '237560', '237590', '237637',
'237733', '237731', '237655', '238890', '238910', '238837',
'238926', '238972', '238925', '239755', '239696', '239898',
'240037', '239909', '240036', '240082', '240097', '240526',
'240770', '678151', '678950', '678985'];
let arry=[]
ar.map(arr=>{
arry.push(parseInt(arr))
});


console.log(arry);

使用Array.from来做这个,试试这个:

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