SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Addict
    Join Date
    May 2007
    Posts
    242
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Variable Type Problem

    Hello. I use below code to get the end result as int for a and b variables but javascript behaves new assignments as strings. What is the problem here? Cant I change a variable type from string to number at run time?

    PHP Code:
    var a="";
    var 
    b="";
    for (
    i=0;i<2;i++) {

    +=5;
    +=5;
    }
    alert(a); 

  2. #2
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,609
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That's just the way Javascript is with no typecasting. The + operator assumes a String unless you force the type to be a Number ...

    Code JavaScript:
    var a = "";
    var b = "";
     
    for (i=0;i<2;i++) {
    	a = (1 * a) + 5;
    	b += 5;
    }
     
    alert("a = " + a + "; b = " + b);
    Ian Anderson
    www.siteguru.co.uk

  3. #3
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In JavaScript, the plus sign (+) performs two duties. It concatenates strings and it adds numbers. Unlike other operators, it doesn't convert strings to numbers before performing operations on them.

    Instead of setting those two variables to an empty string initially, set them to 0.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  4. #4
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,609
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    As proven by ...
    Code JavaScript:
    var a = "";
    var b = 0;
     
    for (i=0;i<2;i++) {
    	a = (1 * a) + 5;
    	b += 5;
    }
     
    alert("a = " + a + "; b = " + b);
    (Note the slight edit from my previous post)
    Ian Anderson
    www.siteguru.co.uk

  5. #5
    SitePoint Addict
    Join Date
    May 2007
    Posts
    242
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks both of you, have seen the trick.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •