459,253 Members | 1,689 Online
Need help? Post your question and get tips & solutions from a community of 459,253 IT Pros & Developers. It's quick & easy.

# split() quirk

 P: n/a Why does ''.split(',') yield an array with length 1 rather than an array with length 0? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome. Jul 23 '05 #1
5 Replies

 P: n/a Christopher Benson-Manica wrote: 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 -- Fred Jul 23 '05 #2

 P: n/a Fred Oz spoke thus: 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. -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome. Jul 23 '05 #3

 P: n/a 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" wrote in message news:42***********************@per-qv1-newsreader-01.iinet.net.au... Christopher Benson-Manica wrote: 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 -- Fred Jul 23 '05 #4

 P: n/a JRS: In article , dated Fri, 25 Feb 2005 14:43:16, seen in news:comp.lang.javascript, Christopher Benson-Manica posted : Why does ''.split(',') yield an array with length 1 rather than anarray 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. -- © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Delphi 3 Turnpike 4 © TP/BP/Delphi/&c., FAQqy topics & links; clpdmFAQ; news:borland.* Guidelines Jul 23 '05 #5

 P: n/a Chris wrote: 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. :-) -- Fred Jul 23 '05 #6

### This discussion thread is closed

Replies have been disabled for this discussion.