Didier Levy
Didier Levy

Reputation: 3453

javascript problem with implicitly typed variables

Forgive this novice question (novice in Javascript!).

In a html page I have a set of images with a name and a number: img1 img2 img3... img12... And there is a JS function where I need to iterate from (say) img5 to last img.

If I write this:

function iterateImg(objImgID) {var imgNum = objImgID.replace("img","");
    for (i=imgNum+1;i<20;i++)
    .../...

The variable "i" is treated as a string, and i+1 receive the value "51" if the passed object's ID is img5.

Of course I can still iterate from 1 to n and only perform the desired task when the value of i reaches 6, but that would be an ugly fix.

How can I fix this please? How can I create a variable that will be treated as an integer before I use it as seed? Besides, what would you recommend as best practice?

Upvotes: 1

Views: 70

Answers (4)

JaredPar
JaredPar

Reputation: 754833

Use parseInt to convert the string to a number

var imgNum = parseInt(objImgID.replace("img", ""));

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

var imgNum = parseInt(objImgID.replace("img",""), 10);

Now when you do var i=imgNum+1, it will perform addition of 2 integers.

Upvotes: 0

pimvdb
pimvdb

Reputation: 154858

There are several ways to force JavaScript to convert it into a number

  • parseInt(x, 10) - the 10 is the base of the number
  • x - 0 - subtracting only works for numbers
  • x * 1 - multiplying also

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78530

var imgNum = Number(objImgID.replace("img",""));

That'll do it.

Or better yet (because I love regex)

var imgNum = Number(objImgID.match(/[0-9]+/));

Upvotes: 1

Related Questions