質問

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?

役に立ちましたか?

解決

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

That'll do it.

Or better yet (because I love regex)

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

他のヒント

Use parseInt to convert the string to a number

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

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
var imgNum = parseInt(objImgID.replace("img",""), 10);

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top