开发者

javascript problem with implicitly typed variables

开发者 https://www.devze.com 2023-03-31 18:52 出处:网络
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...

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消