Benjamin Allison
Benjamin Allison

Reputation: 2152

jQuery: why is an integer being added to a variable like a string?

So I'm trying to take the variable that increments in a for statement, and add an integer to it... but for some reason, it's adding the integer as though it were a string; other operations like subtraction or multiplication work as expected.

Why is this happening? Edit: I've added the whole function; the problem in question is where I try to add 2 to the variable x.

What confuses me is that I'm able to use x no problem, in an .eq() object for example...

$(function() {
    $('textarea').bind('paste', function (e){
        inputGroup = $(this).parent();
        var ob = $(this);
        if (e.type == 'paste'){
            setTimeout(function(){
                var data = ob.val();
                var tabbed = data.replace(/\n/g, "\t");
                var cells = tabbed.split("\t");
                for(var x in cells) {
                    foo = x + 2;
                    alert(foo);
                    $(inputGroup).find('input').eq(x).val(cells[x]);
                }
            }, 1);
        }
    });
});

Upvotes: 1

Views: 2404

Answers (4)

Travis Webb
Travis Webb

Reputation: 15018

Why is this happening?

Because x is a string that just looks like a number. Cast to Number first and you'll get the result you expect:

"1" + 2 = "12"
Number("1") + 2 = 3

EDIT : Now that I see you are using split to turn a string into an array, your problem is definitely that you are concatenating strings. Cast to Number first, and your problem is solved.

Yes other arithmetic operations will work, since they will implicitly cast the operands to Numbers. Confusingly, "2" * 3 will in fact evaluate to the integer 6. Welcome to Javascript.

-tjw

Upvotes: 5

Dave Ward
Dave Ward

Reputation: 60580

As others have mentioned, x is a string. That's why.

There's a nice trick for casting strings as numbers in JavaScript that hasn't been mentioned though:

for(var x in cells) {
  // Without the "var" here, you're setting a global
  //  variable during each loop iteration.
  var foo = +x + 2;

  $(inputGroup).find('input').eq(foo).val(cells[x]);
}

Upvotes: 0

Alex
Alex

Reputation: 66002

Without more code, specifically the initialization of cells, I can't tell you the exact reason. But you can simply call parseInt() on x to turn it into an integer for addition

for(var x in cells) {
    foo = parseInt(x, 10) + 2;
    $(inputGroup).find('input').eq(foo).val(cells[x]);
}

Upvotes: 2

mVChr
mVChr

Reputation: 50195

Because + is a String concatenation but there is no equivalent String method for * or / so when using those it cast the value as a Number. Just cast x as an integer:

for(var x in cells) {
    foo = parseInt(x, 10) + 2;
    $(inputGroup).find('input').eq(foo).val(cells[x]);
}

The 10 in parseInt is saying to use a base 10 number system (as opposed to hex 16, e.g.).

Upvotes: 0

Related Questions