The confusion about the split() function of JavaScript with an empty string

First I set a variable, and set it to empty:

var str = "";

Then I split it through "&":

var strs = str.split('&');

In the end, I show strs's length:

alert( strs.length);

It alert "1".

But I assign nothing to the 'str' variable. Why does it still have a length, should't it be zero?


Solution 1:

From the MDC doc center:

Note: When the string is empty, split returns an array containing one empty string, rather than an empty array.

Read the full docs here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split

In other words, this is by design, and not an error :)

Solution 2:

Because you get an array that contains the empty string:

[ "" ]

That empty string is one element. So length is 1.