문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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) );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top