How to prevent values from being converted to strings in javascript?

前端 未结 5 1728
灰色年华
灰色年华 2021-01-20 16:58
    var str;
    var displayedNum;
    for (i in imgURLArray){
        str = \"
  • \" + \"\"+ (1+i) + \"\" + \"
  • \
    相关标签:
    5条回答
    • 2021-01-20 17:07

      Try wrapping numbers in Number()

      Like:

      var i = 1;
      
      var str = "foobar" + Number(1+i) + "other stuff";
      
      0 讨论(0)
    • 2021-01-20 17:08
      var str = "foobar" + (1+i) + "other stuff";
      
      0 讨论(0)
    • 2021-01-20 17:11

      Use parenthesis:

      var str = "foobar" + (1+i) + "other stuff";
      

      I have the same problem if I try to do the addition outside of the string and store in a variable as well, it still converts to string instead of doing addition.

      It should not. My guess is that you are doing something wrong there too.

      Update: It seems you are converting i to a string somewhere in the code you did not post.

      Update 2: Don't use for..in to loop over an array. Use a normal for loop if it is really an array:

      for(var i = 0, l = imgURLArray.length; i < l; i++)
      

      But if it is an objects:

      for...in will always set i as a string (as it loops over the properties of the object which are not always integers) . That means you would have to convert i before you do any addition:

      ... + (1 + (+i)) + ...
      

      Update 3:

      You don't always have to use such an "explicit" for loop. For example, you can traverse the array in reverse order, which makes the head shorter:

      for (var i = imgURLArray.length; i--; ) {
          str = "<li photonum="+i+">" + "<a>"+ (1+i) + "</a>" + "</li>";
          $("ul.selection-list").prepend(str);
      }
      
      0 讨论(0)
    • 2021-01-20 17:14

      You could just use the parseInt method:

      var str = "foobar" + (parseInt(1+i)) + "other stuff";
      
      0 讨论(0)
    • 2021-01-20 17:19

      The reason is due to your loop:

      for (i in imgURLArray){
      

      This iterates over all the property names of imgURLArray as strings. So you will need to use Number() to convert i to an integer:

          str = "<li photonum="+i+">" + "<a>"+ (1+Number(i)) + "</a>" + "</li>";
      
      0 讨论(0)
    提交回复
    热议问题