Javascript将字符串数组的数组转换为数字数组的数组

时间:2017-01-12 10:04:35

标签: javascript arrays string

我是Javascript的新手,我正在寻找最好的转换方式

x=[[["0","0"],["1","1"],["2","1.5"]],[["0","0.1"],["1","1.1"],["2","2"]]]

进入

[[[0,0],[1,1],[2,1.5]],[[0,0.1],[1,1.1],[2,2]]]

除了使用两个for循环来实现此方法之外,JS中是否有任何快捷方式?

2 个答案:

答案 0 :(得分:3)

您可以对嵌套数组使用递归方法。

var x = [[["0", "0"], ["1", "1"], ["2", "1.5"]], [["0", "0.1"], ["1", "1.1"], ["2", "2"]]],
    result = x.map(function iter(a) {
        return Array.isArray(a) ? a.map(iter) : +a;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

使用嵌套的Array#map方法。

x = [
  [
    ["0", "0"],
    ["1", "1"],
    ["2", "1.5"]
  ],
  [
    ["0", "0.1"],
    ["1", "1.1"],
    ["2", "2"]
  ]
];

var res = x.map(function(arr) {
  return arr.map(function(arr1) {
    return arr1.map(Number);
  });
})

console.log(res);


使用ES6 arrow function

x = [
  [
    ["0", "0"],
    ["1", "1"],
    ["2", "1.5"]
  ],
  [
    ["0", "0.1"],
    ["1", "1.1"],
    ["2", "2"]
  ]
];

var res = x.map(arr => arr.map(arr1 => arr1.map(Number)));

console.log(res);