最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why "".split(" ").length returns 1? - Stack Overflow

programmeradmin2浏览0评论

Why the code below returns 1? That doesn't make sense.

var length = "".split(" ").length;
console.log(length);

Why the code below returns 1? That doesn't make sense.

var length = "".split(" ").length;
console.log(length);

Share Improve this question edited Jul 1, 2018 at 19:48 Ivar 6,86812 gold badges56 silver badges67 bronze badges asked Jul 1, 2018 at 19:39 Tomás Hugo AlmeidaTomás Hugo Almeida 1301 silver badge8 bronze badges 1
  • 4 Possible duplicate of What does split() returns if the string has no match – Ivar Commented Jul 1, 2018 at 19:52
Add a ment  | 

4 Answers 4

Reset to default 6

Because split will return original string if there wasn't split char in that string.

like:

"".split(" ")
// [""]
"a".split(" ")
// ["a"]

String.prototype.split()

Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

split returns array [""] which length is 1.

split will "break up" the string when a match is found, so:

"something".split("different");

Will not break up the string, resulting in:

["something"]

The same applies to an empty string.

Simply put, it will split the string at every " ", though since the string doesn't have any " ", it will be an array with only one item holding the original string itself, no matter that string is empty or not, hence length is 1.

Below samples shows the length if there were just one " " in the string, ending in ["",""].

console.log( "".split("").length );

console.log( "".split(" ").length );

console.log( " ".split(" ").length );

发布评论

评论列表(0)

  1. 暂无评论