在javascript中将字符串转换为二维数组

时间:2022-06-13 21:20:07

I'm trying to convert a string like this "10|15|1,hi,0,-1,bye,2" where the first two elements 10|15 mean something different than 1,hi,0,-1,bye,2. I would like to separate them from each other. A naive way to accomplish that would be:

我正在尝试转换像这样的字符串“10 | 15 | 1,hi,0,-1,bye,2”,其中前两个元素10 | 15表示不同于1的字符,hi,0,-1,bye ,2。我想将它们彼此分开。一种天真的方法是:

value = string.split("|");
var first = value[0];
var second = value[1];
var tobearray = value[2];
array = tobearray.split(",");

(Of course, if you know a way to do this in a better way, I'd be glad to know). However, array is an array which contains array[0]=1, array[1]=hi, array[2]=0, array[3]=-1, etc. However, I want to obtain a two dimensional array such as

(当然,如果你知道以更好的方式做到这一点的方法,我会很高兴知道)。但是,数组是一个数组,其中包含数组[0] = 1,数组[1] = hi,数组[2] = 0,数组[3] = - 1等。但是,我想获得一个二维数组,如如

array[0][0]=1, array[0][1]=hi, array[0][2]=0
array[1][0]=-1, array[1][1]=bye, array[1][2]=2

Is there any way to do that?

有没有办法做到这一点?

Thanks

谢谢

3 个解决方案

#1


16  

The first two elements (10|15) can be extracted beforehand. After that you're left with:

可以预先提取前两个元素(10 | 15)。之后你就离开了:

var a = "1,hi,0,-1,bye,2";

Let's splice until we're left with nothing:

让我们拼接,直到我们什么都没有留下:

var result = [];

a = a.split(','); 

while(a[0]) {
    result.push(a.splice(0,3));
}

result; // => [["1","hi","0"],["-1","bye","2"]]

#2


3  

function getMatrix(input_string) 
{
    var parts = input_string.split('^');
    for (var t=0; t<parts.length; t++)
    {
        var subparts = parts[t].split('*');

        parts[t] = subparts.splice(0,subparts.length);              
    }

    return parts;
}

#3


2  

function getMatrix(input_string) {
    var parts = input_string.split('|');
    var subparts = parts.pop().split(',');
    var partlen = subparts.length / parts.length;
    for (var i=0; i<parts.length; i++) {
        parts[i] = subparts.splice(0,partlen);
    }
    return parts;
}

#1


16  

The first two elements (10|15) can be extracted beforehand. After that you're left with:

可以预先提取前两个元素(10 | 15)。之后你就离开了:

var a = "1,hi,0,-1,bye,2";

Let's splice until we're left with nothing:

让我们拼接,直到我们什么都没有留下:

var result = [];

a = a.split(','); 

while(a[0]) {
    result.push(a.splice(0,3));
}

result; // => [["1","hi","0"],["-1","bye","2"]]

#2


3  

function getMatrix(input_string) 
{
    var parts = input_string.split('^');
    for (var t=0; t<parts.length; t++)
    {
        var subparts = parts[t].split('*');

        parts[t] = subparts.splice(0,subparts.length);              
    }

    return parts;
}

#3


2  

function getMatrix(input_string) {
    var parts = input_string.split('|');
    var subparts = parts.pop().split(',');
    var partlen = subparts.length / parts.length;
    for (var i=0; i<parts.length; i++) {
        parts[i] = subparts.splice(0,partlen);
    }
    return parts;
}