Question

I've got a small problem with javascript that could be illustrated by following example:

function inlineSplit ( string, delimeter )
{
    delimiter = typeof delimeter !== 'undefined' ? delimeter : ",";
    return new Array( string.split(delimiter) );
}

I would assume, that after performing following operation the test variable would be an array:

var test = inlineSplit( "a,b,c" );

To my surprise, function returns a single string. In a following test:

alert( test[0] ); // results in "a,b,c"
alert( test[1] ); // results in ""

What may be wrong? It's been a long time since I coded in javascript, and right now I'm beginning to feel kind of dumb not understanding what's exactly wrong... :(

Was it helpful?

Solution

The .split() function returns an array; there's no need to build one. Your code builds a new array that will have one entry, the array returned by .split().

An easier way to build an array is to use an array literal:

return [1, 2, 3];

Whatever you pass in to the alert() function will be coerced to a string, so it's not the best way to analyze behavior.

OTHER TIPS

you are putting an array in an another array that's because alert( test[0] ); returning you the first array that you made by spliting your string.

use

 return string.split(delimiter);

instead of

return new Array( string.split(delimiter) );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top