有一段代码不是特别明白

ffeitian 发布于 4月前 | 更新于 4月前
无人欣赏。

有一段代码不是特别明白

下面这段js代码,为什么每个标点(例如"," ".")会产生出一个''

```js

const p = "Bob hit a ball, the hit BALL flew far after it was hit.";

const words1 = p.toLowerCase().split(/W/);

console.log(words1);

```

结果是: [ 'bob', 'hit', 'a', 'ball', '', 'the', 'hit', 'ball', 'flew', 'far', 'after', 'it', 'was', 'hit', '' ]

共2条回复
tinyfool 回复于 4月前

这个答案很简单啊,你弄明白split是啥就可以了

ffeitian 回复于 4月前

1楼 @tinyfool 谢谢,大概明白了

如果'AAAwAAAAAwAAAw'以w字符为分隔的话,得到['AAA', 'AAAA', 'AAA', '']

如果'AAAwAAAAAwwAAAw'以w字符为分隔的话,得到['AAA', 'AAAA', '', 'AAA', '']

如果'wAAAwAAAAAwAAAw'以w字符为分隔的话,得到['', 'AAA', 'AAAA', 'AAA', '']

```

const s1 = 'AAAwAAAAAwAAAw';

const s2 = 'AAAwAAAAAwwAAAw';

const s3 = 'wAAAwAAAAAwAAAw';

const ss1 = s1.split(/w/);

const ss2 = s2.split(/w/);

const ss3 = s3.split(/w/);

console.log(ss1);

console.log(ss2);

console.log(ss3);

```

output:

[ 'AAA', 'AAAAA', 'AAA', '' ]

[ 'AAA', 'AAAAA', '', 'AAA', '' ]

[ '', 'AAA', 'AAAAA', 'AAA', '' ]

登录 或者 注册