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

Ash*_*win 160 javascript arrays

我有以下字符串 -

var a = "1,2,3,4";
Run Code Online (Sandbox Code Playgroud)

当我做 -

var b = a.split(',');
Run Code Online (Sandbox Code Playgroud)

我知道b["1", "2", "3", "4"]

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

tec*_*bar 372

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

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

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});
Run Code Online (Sandbox Code Playgroud)

检查文档


或者更优雅的用户指出:thg435

var b = a.split(',').map(Number);
Run Code Online (Sandbox Code Playgroud)

其他地方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;
};
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`map(Number)`. (82认同)
  • 文档中的["Tricky用例"](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map#Tricky_use_case)实际上讨论了这个主题. (2认同)
  • 要将字符串转换为数字数组,请使用空字符串作为分隔符:`'1234567'.split('').map(Number);` (2认同)
  • 值得注意的是 Number() 不会强制整数,只有数字。如果您需要专门转换为整数,请使用 parseInt()。`"1.1,2,3".split(",").map(Number)` 是 `[1.1, 2, 3]` 而 `"1.1,2,3".split(",").map( item =&gt; parseInt(item, 10))` 是 `[1, 2, 3]` (2认同)
  • @Sachith - parseInt() 的第二个参数是基础。在本例中为 10。参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt (2认同)

Tra*_*pII 103

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

b="1,2,3,4".split`,`.map(x=>+x)
Run Code Online (Sandbox Code Playgroud)

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

我希望它更清楚一点。

  • 为什么会这样?看起来不优雅,因为它太抽象了。 (5认同)
  • @SafeFastExpressive 因为这是“高尔夫球手”的版本,如果您不知道我在说什么:https://codegolf.stackexchange.com/ (3认同)
  • 为什么我们要关心map函数使用了多少个字符? (2认同)
  • 很聪明,但如果同事在实际代码中包含这样的内容,我会踢他们。 (2认同)

Q10*_*ing 40

这个很简单,比如:

["1", "2", "3", "4"].map(i=>Number(i))
Run Code Online (Sandbox Code Playgroud)

你可以运行演示。

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

  • 或者简单地:`.map(Number)` (2认同)

Mat*_*ert 17

将其映射到整数:

a.split(',').map(function(i){
    return parseInt(i, 10);
})
Run Code Online (Sandbox Code Playgroud)

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

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

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


xda*_*azz 15

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

"1,2,3,4".split(',').map(function(el){ return +el;});
Run Code Online (Sandbox Code Playgroud)


Aym*_*men 15

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

var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);
Run Code Online (Sandbox Code Playgroud)

b 是一个数字数组

  • 这是我发现的最简单的方法! (2认同)

nic*_*ael 9

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

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


Pra*_*hor 7

一个班轮

Array.from(a.split(','), Number)
Run Code Online (Sandbox Code Playgroud)


ank*_*zet 5

无需使用 lambda 和/或radix向 提供参数parseInt,只需使用parseFloatorNumber即可。

理由:

  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
    
    Run Code Online (Sandbox Code Playgroud)
  2. 它更短。

  3. 当-approach - 不这样做时,它会快一点并且利用缓存parseInt

      // 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'! >_<
    
    Run Code Online (Sandbox Code Playgroud)

注意:在 Firefox 中,parseInt运行速度大约是其他浏览器的 4 倍,但仍然比其他浏览器慢。总计:+e<<<NumberparseFloatparseInt


Sah*_*mar 5

为此,请使用Array.from ,尝试以下操作:

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