Square each number in an array in javascript

后端 未结 14 1028
悲&欢浪女
悲&欢浪女 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:03

    Best way to Square each number in an array in javascript

    Array.prototype.square = function () {
        var arr1 = [];
        this.map(function (obj) {
            arr1.push(obj * obj);
        });
        return arr1;
    }
    arr = [1, 6, 7, 9];
    console.log(arr.square());
    arr1 = [4, 6, 3, 2];
    console.log(arr1.square())
    
    0 讨论(0)
  • 2020-12-16 09:04
    function squareDigits(num){
      //may the code be with you
      var output = [];
      var splitNum = num.toString();
       for(var i = 0; i < splitNum.length; i++){
         output.push(splitNum.charAt(i))
        }
    
       function mapOut(){
        var arr = output;
        return arr.map(function(x){
            console.log(Math.pow(x, 2));
        })
       }
       mapOut();
    }
    
    squareDigits(9819);
    

    This should work

    0 讨论(0)
  • 2020-12-16 09:05

    Math.sqrt gives you square root not square of a number. Use Math.pow with second argument of 2.

    0 讨论(0)
  • 2020-12-16 09:06

    Avoid unnecessary loops, use map()function

    let array = [1,2,3,4,5];
    function square(a){            // function to find square
      return a*a;
    }
    arrSquare = array.map(square);    //array is the array of numbers and arrSquare will be an array of same length with squares of every number
    

    You can make the code shorter like this:

    let array = [1,2,3,4,5];
    arrSquare = array.map(function (a){return a*a;});
    
    0 讨论(0)
  • 2020-12-16 09:07

    The original code is taking the square root of the value. The second version is multiplying the value with itself (squaring it). These are inverse operations

    0 讨论(0)
  • 2020-12-16 09:07
    function map(square,a) {
      var result = [];
      for(var i=0;i<=a.length-1;i++)
       result[i]=square(a[i]);
      return result;
    }
    
    var square = function(x) {
       return x*x;
    }
    
    var value=[1,2,3,4];
    var final= map(square,value);
    console.log(final);
    

    You can also try the above code snippet.

    0 讨论(0)
提交回复
热议问题