0

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... :(

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, that's the answer :)
1

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) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.