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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19418244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:31:11  来源:igfitidea点击:

Elegant way to convert string of Array of Arrays into a Javascript array of arrays?

javascriptarrays

提问by cesarferreira

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 notelegant at all.

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

Do you guys have any suggestions?

大家有什么建议吗?

回答by Marty

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.

不过,如果可能,我建议更正服务器上的输出。

回答by Chris Martin

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

这个解决方案在实践中是愚蠢的——绝对JSON.parse像其他人所说的那样使用——但为了享受正则表达式的乐趣,你去吧:

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]");

回答by meagar

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。

回答by Felix

In a function

在一个函数中

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

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

回答by Todd

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 上打字,所以我提前为任何错别字道歉。