1

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?

1
  • Don't forget to declare 'i' with var. If you don't, 'i' may get attached to the global scope (window). Commented Aug 29, 2011 at 19:14

4 Answers 4

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

That'll do it.

Or better yet (because I love regex)

var imgNum = Number(objImgID.match(/[0-9]+/));
Sign up to request clarification or add additional context in comments.

3 Comments

Guys, I have to tank you all! 4 answers in less than 10 minutes, that's great!
Is there a functional difference between using Number and parseInt or is it just a matter of style?
For those interested. It looks like there is at least a minor functional difference. For example Number(true) === 1 and parseInt(true) results in NaN
1

Use parseInt to convert the string to a number

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

Comments

0

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

Comments

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

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

2 Comments

ok so why are you guys using parseInt() instead of Number()? I'm going to assume there's some kind of speed aspect or something?
@Joseph, performance would be pretty equivalent but if you are interested in concrete numbers take a look here: jsperf.com/number-vs-parseint-vs-plus/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.