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

前端 未结 5 1776
灰色年华
灰色年华 2021-01-20 16:58
    var str;
    var displayedNum;
    for (i in imgURLArray){
        str = \"
  • \" + \"\"+ (1+i) + \"\" + \"
  • \
    5条回答
    •  死守一世寂寞
      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 = "
    • " + ""+ (1+i) + "" + "
    • "; $("ul.selection-list").prepend(str); }

    提交回复
    热议问题