且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript:将字符串拆分为二维数组

更新时间:2022-11-14 16:21:36

您可以使用替换以获得更紧凑的代码:

You can use replace to get more compact code:

var months= "2010_1,2010_3,2011_4,2011_7";
var monthArray2d = []

months.replace(/(\d+)_(\d+)/g, function($0, $1, $2) {
    monthArray2d.push([parseInt($1), parseInt($2)]);
})

地图,如果您的目标浏览器支持的话:

or map if your target browser supports it:

monthArray2d = months.split(",").map(function(e) {
    return e.split("_").map(Number);
})

基本上,第一个函数看起来用于年/月模式数字下划线数字,并将每个找到的子字符串存储在数组中。当然,您可以使用其他定界符代替下划线。该函数不关心值的定界符(逗号),因此可以是任意值。示例:

Basically, the first function looks for year/month patterns "digits underscore digits", and stores each found substring in an array. Of course, you can use other delimiters instead of underscore. The function doesn't care about the values' delimiter (comma), so that it can be whatever. Example:

var months= "2010/1 ... 2010/3 ... 2011/4";
months.replace(/(\d+)\/(\d+)/g, function($0, $1, $2) {
    monthArray2d.push([parseInt($1), parseInt($2)]);
})