将数组的字符串转换为数组的Javascript数组的优雅方法?

时间:2021-02-22 20:22:14

I have an ajax request that returns a list of values like this:

我有一个ajax请求,它返回如下值列表:

"[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

I need it to be a javascript array with numbers:

我需要它是一个带有数字的javascript数组:

[[-5, 5, 5], [-6, 15, 15], [7, 13, 12]]

I tried to replace the '[' and ']' for a '|' and then split by '|' and foreach item split by ',' and add them to an array, but this is not elegant at all.

我试图将'['和']'替换为'|',然后将'|'分割为',并将它们添加到数组中,但这一点都不优雅。

Do you guys have any suggestions?

你们有什么建议吗?

5 个解决方案

#1


17  

You can use JSON.parse() to convert that string into an array, as long as you wrap it in some brackets manually first:

您可以使用JSON.parse()将该字符串转换为数组,只要您先手工将其封装在一些括号中:

var value = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var json = JSON.parse("[" + value + "]");

console.log(json);

I would suggest correcting the output at the server if possible, though.

不过,如果可能的话,我建议在服务器上修改输出。

#2


2  

This solution is stupid in practice -- absolutely use JSON.parse as others have said -- but in the interest of having fun with regular expressions, here you go:

这个解决方案在实践中很愚蠢——绝对要使用JSON。正如其他人所说的那样进行解析——但为了让正则表达式更有趣,这里有:

function getMatches(regexp, string) {
  var match, matches = [];
  while ((match = regexp.exec(string)) !== null)
    matches.push(match[0]);
  return matches;
}

function parseIntArrays(string) {
  return getMatches(/\[[^\]]+\]/g, string)
    .map(function (string) {
      return getMatches(/\-?\d+/g, string)
        .map(function (string) { 
          return parseInt(string); 
        });
    });
}

parseIntArrays("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]");

#3


1  

In a function

在一个函数中

var strToArr = function(string){ return JSON.parse('[' + string + ']')}

console.log(strToArr("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"));

#4


1  

var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var arr = [];
var tmp = string.split('], ');

for (var i=0; i<tmp.length; i++) {
    arr.push(tmp[i].replace(/\[|\]/g, '').split(', '));
}

Typing on my iPad so I apologize in advance for any typos.

在我的iPad上输入,所以我为任何拼写错误提前道歉。

#5


0  

If you're generating the data, and you trust it, just use eval:

如果您正在生成数据,并且信任它,请使用eval:

var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

var arrays = eval('[' + string + ']');

Alternatively, start returning well-formed JSON.

或者,开始返回格式良好的JSON。

#1


17  

You can use JSON.parse() to convert that string into an array, as long as you wrap it in some brackets manually first:

您可以使用JSON.parse()将该字符串转换为数组,只要您先手工将其封装在一些括号中:

var value = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var json = JSON.parse("[" + value + "]");

console.log(json);

I would suggest correcting the output at the server if possible, though.

不过,如果可能的话,我建议在服务器上修改输出。

#2


2  

This solution is stupid in practice -- absolutely use JSON.parse as others have said -- but in the interest of having fun with regular expressions, here you go:

这个解决方案在实践中很愚蠢——绝对要使用JSON。正如其他人所说的那样进行解析——但为了让正则表达式更有趣,这里有:

function getMatches(regexp, string) {
  var match, matches = [];
  while ((match = regexp.exec(string)) !== null)
    matches.push(match[0]);
  return matches;
}

function parseIntArrays(string) {
  return getMatches(/\[[^\]]+\]/g, string)
    .map(function (string) {
      return getMatches(/\-?\d+/g, string)
        .map(function (string) { 
          return parseInt(string); 
        });
    });
}

parseIntArrays("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]");

#3


1  

In a function

在一个函数中

var strToArr = function(string){ return JSON.parse('[' + string + ']')}

console.log(strToArr("[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"));

#4


1  

var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]";
var arr = [];
var tmp = string.split('], ');

for (var i=0; i<tmp.length; i++) {
    arr.push(tmp[i].replace(/\[|\]/g, '').split(', '));
}

Typing on my iPad so I apologize in advance for any typos.

在我的iPad上输入,所以我为任何拼写错误提前道歉。

#5


0  

If you're generating the data, and you trust it, just use eval:

如果您正在生成数据,并且信任它,请使用eval:

var string = "[-5, 5, 5], [-6, 15, 15], [7, 13, 12]"

var arrays = eval('[' + string + ']');

Alternatively, start returning well-formed JSON.

或者,开始返回格式良好的JSON。