Square each number in an array in javascript

后端 未结 14 1027
悲&欢浪女
悲&欢浪女 2020-12-16 08:36

I\'m trying to square each number in an array and my original code didn\'t work. I looked up another way to do it, but I\'d like to know WHY the original code didn\'t work.<

相关标签:
14条回答
  • 2020-12-16 09:08

    Here is how it can be done, using a simple method called .forEach

    var numbers = [1,2,3,4,5,6,7,8];
    numbers.forEach(function(element, index, array){
        array[index] = element* element;
    });
    console.log(numbers);
    
    0 讨论(0)
  • 2020-12-16 09:11

    The first sample is taking the square root, not squaring the value. To square you want to use

    Math.pow(arr[i],2);
    
    0 讨论(0)
提交回复
热议问题