我玩弄了一些代码,然后遇到了奇怪的行为。您能告诉我为什么这些表达式产生不同的输出吗?
const a = 'abcd';
const b = a.split(/\b|\B/);
console.log('b: ', b);
const c = a.split(/(\b|\B)/);
console.log('c: ', c);
const d = a.split(/(\b|\B){0}/);
console.log('d: ', d);
const e = a.split(/(\b|\B)(?=(\b|\B){0})/);
console.log('e: ', e);
const f = a.split(/(\b|\B){0}(?=(\b|\B){0})/);
console.log('f: ', f);
输出为:
b: [ 'a', 'b', 'c', 'd' ]
c: [ 'a', '', 'b', '', 'c', '', 'd' ]
d: [ 'a', undefined, 'b', undefined, 'c', undefined, 'd' ]
e: [ 'a', '', undefined, 'b', '', undefined, 'c', '', undefined, 'd' ]
f: [ 'a',
undefined,
undefined,
'b',
undefined,
undefined,
'c',
undefined,
undefined,
'd' ]
答案 0 :(得分:1)
来自ECMA:
String.prototype.split(分隔符,限制)
如果分隔符是包含捕获括号的正则表达式,则每次将分隔符匹配时,捕获括号的结果(包括任何未定义的结果)都会被拼接到输出数组中。
每个示例c,d,e和f中,捕获组的结果都被拼接成结果数组。