我是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中是否有任何快捷方式?
答案 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);
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);