split() quirk

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

Why does ''.split(',') yield an array with length 1 rather than an
array with length 0?
 
F

Fred Oz

Christopher said:
Why does ''.split(',') yield an array with length 1 rather than an
array with length 0?

Because the first element of the array will be everything up to
the first ','. You have created an array with one element that
contains nothing. It is equivalent to:

var newArray = [,];

Which has a length of 1, but it contains nothing.


Some examples:

alert( ''.split(',').length) // 1
var z = []; alert(z.length) // 0
var z = [,]; alert(z.length) // 1
 
C

Christopher Benson-Manica

Fred Oz said:
Because the first element of the array will be everything up to
the first ','. You have created an array with one element that
contains nothing. It is equivalent to:

I'm sure it's just me, but it seems counterintuitive to me :) Thanks.
 
C

Chris

var z = [,]; alert(z.length) // 1

returns 2 for me, is it that there's a space before and after the comma?

Chris

Fred Oz said:
Christopher said:
Why does ''.split(',') yield an array with length 1 rather than an
array with length 0?

Because the first element of the array will be everything up to
the first ','. You have created an array with one element that
contains nothing. It is equivalent to:

var newArray = [,];

Which has a length of 1, but it contains nothing.


Some examples:

alert( ''.split(',').length) // 1
var z = []; alert(z.length) // 0
var z = [,]; alert(z.length) // 1
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Fri, 25 Feb 2005
14:43:16, seen in Christopher Benson-Manica
Why does ''.split(',') yield an array with length 1 rather than an
array with length 0?

I have a vague recollection that the result may be browser-dependent.

But what you (and I) get agrees with ECMA 262, Edn 3, 15.5.4.14, para 3,
IMHO.
 
F

Fred Oz

Chris said:
var z = [,]; alert(z.length) // 1

returns 2 for me, is it that there's a space before and after the comma?


No, it's whether you use IE or not. Firefox/Mozilla/Safari all
give 1, but IE gives 2. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top