如果您在遇到零时必须启动一个新数组,您可以求助于
这段代码,希望它不会像vodoo编程一样出现。
var x = [0, 1, 2, 0, 0, 0, 1, 0];
x.join("") /* convert the array to a string */
.match(/(0[^0]*)/g) /* use a regex to split the string
into sequences starting with a zero
and running until you encounter
another zero */
.map(x=>x.split("")) /* get back the array splitting the
string chars one by one */
我假设数组元素只是一个数字长,0 是每个子数组的开始。
删除一位数字的假设将诉诸此代码:
var x = [0, 1, 2, 0, 12, 0, 0, 1, 0];
var the_regexp = /0(,[1-9]\d*)*/g;
x.join(",") /* convert the array to a comma separated
string */
.match(the_regexp) /* this regex is slightly different from
the previous one (see the note) */
.map(x=>x.split(",")) /* recreate the array */
在这个解决方案中,我们用逗号分隔数组元素,让我们检查一下正则表达式:
/0表示每个子数组都以0开头,/是匹配的开始
,[1-9]\d*这个子模式匹配一个整数,如果它前面有一个逗号;第一个数字不能为 0,其他可选数字没有此限制。因此我们匹配 ,1 或 ,200 或 ,9 或 ,549302387439209。
我们必须在子数组中包含我们找到的所有连续的非零数字 (,[1-9]\d*)* 可能没有,因此第二个 *。
`/g' 关闭正则表达式。 g 表示我们想要所有匹配项,而不仅仅是第一个匹配项。
如果您更喜欢单线:
x.join(",").match(/0(,[1-9]\d*)*/g).map(x=>x.split(','));
或者,如果您更喜欢 ECMA2015 之前的函数表达式语法:
x.join(",").match(/0(,[1-9]\d*)*/g).map(function(x){return x.split(',');});