简体   繁体   中英

Convert a javascript string into a 2-dimensional array

I have this data coming from a REST method using jquery's getJSON method.

"[Date.UTC(2010,0,0,0,0,0,0), 157],[Date.UTC(2010,0,0,0,0,420,1), 157],[Date.UTC(2010,0,0,0,0,420,2), 282],[Date.UTC(2010,0,0,0,0,600,3), 282],[Date.UTC(2010,0,0,0,0,600,4), 125],[Date.UTC(2010,0,0,0,0,900,5), 125],[Date.UTC(2010,0,0,0,0,900,6), 282],[Date.UTC(2010,0,0,0,0,2100,7), 282],[Date.UTC(2010,0,0,0,0,2100,8), 125],[Date.UTC(2010,0,0,0,0,2400,9), 125],[Date.UTC(2010,0,0,0,0,2400,10), 295],[Date.UTC(2010,0,0,0,0,3600,11), 295],[Date.UTC(2010,0,0,0,0,3600,12), 125],[Date.UTC(2010,0,0,0,0,3900,13), 125],[Date.UTC(2010,0,0,0,0,3900,14), 288],[Date.UTC(2010,0,0,0,0,5100,15), 288],[Date.UTC(2010,0,0,0,0,5100,16), 125],[Date.UTC(2010,0,0,0,0,5400,17), 125]"

It comes back as a string. I need to parse it into a two dimensional array. Each item in the array should have a date and a value.

I also have full control over the REST method, so I could change the way the data returns. I'm interested in making this as fast as possible.

Here's what we are doing now which I think could be improved:

 var jqxhr = $.getJSON(getDataURL, function(dataResult) {
        var result = dataResult;

        result =result.replace(/\]\,\[/g, ']:[');
        result = result.replace(/\)\,/g, ');');

        var tempArray = result.split(':');

        var myarray = new Array();
        myarray[0] = new Array(2); // Make the first element an array of two elements
        for(i = 0; i < tempArray.length; i ++)
        {
          myarray[i] = tempArray[i].split(';');
          myarray[i][1] = myarray[i][1].replace(/\"/g,'');
          myarray[i][1] = myarray[i][1].replace(/\]/g,'');  
          myarray[i][0] = myarray[i][0].replace(/\[/g,'');                             
        }                                                               
    })

我为此会一fl不振( eval往往会带来安全风险),我只会

var myarray = eval("[" + result + "]");

You should use JSON to return data from your server to your JS script. That will be pretty easier to manipulate it as an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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