# 如何将数字字符串转换为数字数组？

2020/10/17 23:21 · javascript ·  · 0评论

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

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

``````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
``````

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

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

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

`Number()`其余地方在哪里在这里检查

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

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

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

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

Array.from（）有关详细信息，请转到MDN

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

`b` 是一个数字数组

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

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

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

1. 工作正常：

``````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. 它更短。

3. `parseInt`-approach-不这样做时，它会更快一点并利用缓存的优势

``````  // 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'! >_<
``````

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

``````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);
``````

Matt Zeunert的使用Arraw功能的版本（ES6）

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

``````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.
``````

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