Looping Through An Array and Dividing Each Value By 100

后端 未结 5 1228
Happy的楠姐
Happy的楠姐 2021-01-27 03:44

Hey this is my first question and I\'m just finding my way with JS. I have an array which is set, I want to loop through it and divide each value by 100, then print the output t

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 04:22

    divide each value by 100,

    Yes, you want to divide each value by 100, but also store the result back into the array. In JavaScript, if you want to do some calculation and store the results, you need to say

    left-hand-side = calculation
    

    In other words, you need to use the assignment operator (=) to assign the results of the calculation to some variable, array element, or property.

    In your case, the "calculation" is the value of the array element divided by 100, so it would be

    example[i] / 100
    

    You may wonder why example[i/100] does not work. Think about it. The thing that comes inside the [] is an index into the array. You don't want to divide the index i by 100; you want to divide the value at index i by 100.

    The result of this calculation--dividing the element at index i by 100--you want to put back into the array at the same location. So the "left-hand-side" is also element[i]. The entire statement thus is

    example[i] = example[i] / 100;
    

    Your attempt, which was

    ( example [ i/ 100] )
    

    is therefore missing the mark on a couple of levels. First of all, you are dividing the index by 100, instead of dividing the value at the index by 100. Second, you are not assigning the result to anything--so the result will just be thrown away.

    Merely changing the line you knew was shaky, to the above example[i] = example[i] / 100; will make your code work perfectly. You don't need forEach, or map, or arrow functions (although I hope you will learn what they are and start using them sometime soon).

    In this particular case, we are assigning the result of dividing a particular array element by 100 back to that same array element. In such cases, JavaScript provides special assignment operators, which allow you to avoid duplicating the reference to the array element (or variable, or object property). In this case, you're interested in the "division assignment operator", which you can use as

    example[i] /= 100;
               ^^
    

    But there's no particular need to use that, other than brevity.

提交回复
热议问题