简体   繁体   English

将字符串解析为 javascript 中的 2d integer 数组

[英]Parse string into 2d integer array in javascript

I need to parse this string我需要解析这个字符串

d = "1 3 2 1,1 1 2 4,1 1 2 5,1 1 2 6,1 7 2 1,1 8 2 1,1 9 2 1,1 1 3 4,1 1 3 5,1 1 3 6,1 7 3 1,1 1 3 8,1 1 3 9,1 5 4 1,1 6 4 1,1 7 4 1,1 1 4 8,1 1 4 9,1 6 5 1,1 7 5 1,1 1 5 8,1 9 5 1,1 7 6 1,1 8 6 1,1 1 6 9,1 1 7 8,1 9 7 1,1 9 8 1,1 4 3 2,1 2 3 5,1 6 3 2,1 2 3 7,1 2 3 8,1 9 3 2,1 2 4 5,1 2 4 6,1 7 4 2,1 8 4 2,1 2 4 9,1 6 5 2,1 2 5 7,1 2 5 8,1 2 5 9,1 2 6 7,1 2 6 8,1 9 6 2,1 8 7 2,1 2 7 9,1 2 8 9,1 5 4 3,1 3 4 6,1 3 4 7,1 8 4 3,1 3 4 9,1 6 5 3,1 3 5 7,1 3 5 8,1 3 5 9,1 7 6 3,1 3 6 8,1 3 6 9,1 8 7 3,1 3 7 9,1 9 8 3,1 4 5 6,1 4 5 7,1 4 5 8,1 9 5 4,1 7 6 4,1 4 6 8,1 9 6 4,1 4 7 8,1 4 7 9,1 4 8 9,1 7 6 5,1 5 6 8,1 5 6 9,1 8 7 5,1 9 7 5,1 5 8 9,1 6 7 8,1 9 7 6,1 6 8 9,1 9 8 7"

into a 2d array that looks like this:进入一个看起来像这样的二维数组:

d = [[1,3,2,1][1,2,3,4],[1,2,3,4]...... and so on]

where the strings are converted to individual integers.其中字符串被转换为单个整数。

Could someone do this in 10 lines or less?有人能在 10 行或更少的时间内做到这一点吗? I've figured it out but my code is a mess and must be longer than it needs to be我已经想通了,但是我的代码一团糟,必须比需要的更长

edit - here's my crappy code:编辑 - 这是我蹩脚的代码:

let ds = d.split(",");
let temp = [];

for (i= 0; i<=ds.length; i++){
    temp.push([ds[i]])
}
let set = [];
for (i= 0; i<=temp.length-1; i++){

    let t2 = temp[i].toString();
    let t3 = t2.split(" ")
    set.push(t3);
}

for (i= 0; i<=set.length-1; i++){
    for (j= 0; j<=3; j++){
        set[i][j] = Number(set[i][j]);
}
}
console.log(set);

Split by commas, then map each substring to a split on spaces:用逗号分隔,然后 map 每个 substring 以空格分隔:

 const d = "1 3 2 1,1 1 2 4,1 1 2 5,1 1 2 6,1 7 2 1,1 8 2 1,1 9 2 1,1 1 3 4,1 1 3 5,1 1 3 6,1 7 3 1,1 1 3 8,1 1 3 9,1 5 4 1,1 6 4 1,1 7 4 1,1 1 4 8,1 1 4 9,1 6 5 1,1 7 5 1,1 1 5 8,1 9 5 1,1 7 6 1,1 8 6 1,1 1 6 9,1 1 7 8,1 9 7 1,1 9 8 1,1 4 3 2,1 2 3 5,1 6 3 2,1 2 3 7,1 2 3 8,1 9 3 2,1 2 4 5,1 2 4 6,1 7 4 2,1 8 4 2,1 2 4 9,1 6 5 2,1 2 5 7,1 2 5 8,1 2 5 9,1 2 6 7,1 2 6 8,1 9 6 2,1 8 7 2,1 2 7 9,1 2 8 9,1 5 4 3,1 3 4 6,1 3 4 7,1 8 4 3,1 3 4 9,1 6 5 3,1 3 5 7,1 3 5 8,1 3 5 9,1 7 6 3,1 3 6 8,1 3 6 9,1 8 7 3,1 3 7 9,1 9 8 3,1 4 5 6,1 4 5 7,1 4 5 8,1 9 5 4,1 7 6 4,1 4 6 8,1 9 6 4,1 4 7 8,1 4 7 9,1 4 8 9,1 7 6 5,1 5 6 8,1 5 6 9,1 8 7 5,1 9 7 5,1 5 8 9,1 6 7 8,1 9 7 6,1 6 8 9,1 9 8 7"; const arr = d.split(',').map(str => str.split(' ').map(Number) ); console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM