我有一串这样的数字:
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447";
我希望将此字符串转换为2D数组,如下所示:
[[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]]
但是我很难做到。我尝试使用正则表达式:
var result = original.replace(/([-\d.]+),([-\d.]+),?/g, '[$1, $2] ').trim();
但是结果是以下的字符串而不是数组:
[547, 449] [737, 452] [767, 421] [669, 367] [478, 367] [440, 391] [403, 392] [385, 405] [375, 421] [336, 447]
最佳答案
您可以查找介于两者之间的逗号,替换,添加方括号并将其解析为JSON。
var original = "547,449,737,452,767,421,669,367,478,367,440,391,403,392,385,405,375,421,336,447",
array = JSON.parse('[' + original.replace(/\d+,\d+/g, '[$&]') + ']');
console.log(array);
关于javascript - 将以逗号分隔的数字字符串转换为2D数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59609214/