4b0
4b0

Reputation: 22323

For loop gives unexpected result

I am unable to understand the behavior of for loop. jquery:

 $('#btnTest').on("click", function () {

            var thumbUrl = "http:localhost/File/Modules/FileManager/Library/1041323042_12.jpg";
            var arrurl = thumbUrl.split("/");
            var i;
            var result;
            for (i = 0; i < arrurl.length - 1; i++) {
                result += arrurl[i] + '/';
            }
            alert(result);
 });

and html:

<input type="button" class="ThumbLink" value="Test" id="btnTest"/>

But alert gives a result:

undefinedhttp:localhost/File/Modules/FileManager/Library/

Where this undefined comes from.What is my mistake in for loop ?.Thanks.

My jsfiddle:

jsfiddle

Upvotes: 0

Views: 87

Answers (4)

Vijay Singh Rana
Vijay Singh Rana

Reputation: 1090

declare

var result = "";

Then it will work fine :)

Upvotes: 0

Paul
Paul

Reputation: 141829

You must give result an initial value:

var result = '';

Otherwise result is undefined before you concatenate the url onto it:

var x;
x += 'foo';  // x === 'undefinedfoo';

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881403

Maybe, since you're simply appending to result each time through the loop, you may want to set it initially to something other than undefined.

:
var result = "";
for (i = 0; i < arrurl.length - 1; i++) {
    result += arrurl[i] + '/';
}
alert(result);
:

Making that change to your jsfiddle link results in the correct output:

http:localhost/File/Modules/FileManager/Library/

Upvotes: 1

alex
alex

Reputation: 490233

You haven't initialised result to anything, so it will be undefined.

Because you are attempting to concatenate a string to undefined, it will toString() undefined, getting the string "undefined", and will begin to concatenate to that.

You can stop this by initialising result to an empty string ("").

Upvotes: 1

Related Questions