Ben B.
Ben B.

Reputation: 3836

How to prevent values from being converted to strings in javascript?

    var str;
    var displayedNum;
    for (i in imgURLArray){
        str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
        $("ul.selection-list").append(str);

}

I need to do this within a loop, but what happens is it prints out "11" instead of "2", because it converts to string before addition.

I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.

Number(1+1) still converts to string first before turning it into a number, so it comes out 11.

Upvotes: 3

Views: 5922

Answers (5)

Felix Kling
Felix Kling

Reputation: 816870

Use parenthesis:

var str = "foobar" + (1+i) + "other stuff";

I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.

It should not. My guess is that you are doing something wrong there too.

Update: It seems you are converting i to a string somewhere in the code you did not post.

Update 2: Don't use for..in to loop over an array. Use a normal for loop if it is really an array:

for(var i = 0, l = imgURLArray.length; i < l; i++)

But if it is an objects:

for...in will always set i as a string (as it loops over the properties of the object which are not always integers) . That means you would have to convert i before you do any addition:

... + (1 + (+i)) + ...

Update 3:

You don't always have to use such an "explicit" for loop. For example, you can traverse the array in reverse order, which makes the head shorter:

for (var i = imgURLArray.length; i--; ) {
    str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
    $("ul.selection-list").prepend(str);
}

Upvotes: 7

Greg Hewgill
Greg Hewgill

Reputation: 994111

The reason is due to your loop:

for (i in imgURLArray){

This iterates over all the property names of imgURLArray as strings. So you will need to use Number() to convert i to an integer:

    str = "<li photonum="+i+">" + "<a>"+ (1+Number(i)) + "</a>" + "</li>";

Upvotes: 0

Phil.Wheeler
Phil.Wheeler

Reputation: 16858

You could just use the parseInt method:

var str = "foobar" + (parseInt(1+i)) + "other stuff";

Upvotes: 0

c-smile
c-smile

Reputation: 27470

var str = "foobar" + (1+i) + "other stuff";

Upvotes: 0

Marty
Marty

Reputation: 39466

Try wrapping numbers in Number()

Like:

var i = 1;

var str = "foobar" + Number(1+i) + "other stuff";

Upvotes: 1

Related Questions