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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15677869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:39:43  来源:igfitidea点击:

How to convert a string of numbers to an array of numbers?

javascriptarrays

提问by Ashwin

I have below string -

我有以下字符串 -

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

when I do -

当我做 -

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

I get bas ["1", "2", "3", "4"]

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

can I do something to get bas [1, 2, 3, 4]?

我可以做一些事来报复b[1, 2, 3, 4]

采纳答案by TrapII

My 2 cents for golfers:

我给高尔夫球手的 2 美分:

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

backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(','). The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x(which is even shorter than the Numberfunction (5 chars instead of 6)) is equivalent to :

反引号是字符串字面量所以我们可以省略括号(因为 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

I hope it is a bit more clear.

我希望它更清楚一点。

回答by techfoobar

You can use Array.mapto convert each element into a number.

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

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

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

Check the Docs

检查文档



Or more elegantly as pointed out by User: thg435

或者更优雅地如用户所指出的那样:thg435

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

Where Number()would do the rest:check here

Number()剩下的在哪里做:检查这里



Note:For older browsers that don't support map, you can add an implementation yourself like:

注意:对于不支持的旧浏览器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;
};

回答by Matt Zeunert

Map it to integers:

将其映射到整数:

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

maplooks at every array item, passes it to the function provided and returns an array with the return values of that function. mapisn't available in old browsers, but most libraries like jQueryor underscoreinclude a cross-browser version.

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

Or, if you prefer loops:

或者,如果您更喜欢循环:

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

回答by xdazz

+stringwill try to change the string to a number. Then use Array.mapfunction to change every element.

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

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

回答by nicael

A more shorter solution: map and pass the arguments to Number:

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

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

回答by Aymen

Array.from() for details go to MDN

Array.from() 有关详细信息,请访问MDN

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

bis an array of numbers

b是一个数字数组

回答by Q10Viking

This is very simple.Such as:

这个很简单,比如:

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

回答by Mohan Dere

The underscore js way -

下划线 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);

回答by Alexander Myshov

As a variant you can use combiantion _.mapand _.arymethods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:

作为变体,您可以使用lodash 库中组合_.map_.ary方法。整体改造会更加紧凑。以下是官方文档中的示例:

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

回答by ankhzet

There's no need to use lambdas and/or give radixparameter to parseInt, just use parseFloator Numberinstead.

不需要使用 lambdas 和/或给radix参数给parseInt,只需使用parseFloatNumber代替。

Reasons:

原因:

  1. It's working:

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

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

注意:在 Firefox 中的parseInt运行速度大约快 4 倍,但仍然比其他的慢。总计:+e< Number< parseFloat<parseInt