Javascript:将字符串拆分为二维数组 [英] Javascript: split string into 2d array
问题描述
我有一连串的月份和年份:
I have a string of month and years:
var months= "2010_1,2010_3,2011_4,2011_7";
我想将其变成2d数组,其中年份在每个数组的第一个位置,并且第二个月。换句话说,我想以此结尾:
I want to make this into a 2d array with the year in the first position of each array and the month in the second position. In other words, I want to end up with this:
var monthArray2d = [[2010,1],[2010,3][2011,4],[2011,7]];
我目前的操作方式是:
//array of selected months
var monthArray = months.split(",");
//split each selected month into [year, month] array
var monthArray2d = new Array();
for (var i = 0; i < monthArray.length; i++) {
monthArray2d[i] = monthArray[i].split("_");
有没有一种方法可以压缩该代码,所以我永远不需要使用 monthArray
var?
Is there a way to condense that code so that I never need to use the monthArray
var?
推荐答案
您可以使用替换
以获得更紧凑的代码:
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)]);
})
这篇关于Javascript:将字符串拆分为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!