简体   繁体   中英

My math.pow is return NaN when I call it on an array with numerical values. How do I get the square of an array element

I have a function with an array of numbers, I want to square it but I want them in the array box like [4,9,16] Each time i try to do that, it throws back a NAN output in the console. The numbers come back listed as in a straight line.

digit = (num) => {
  let digits = String(num).split('').map(Number);
  for (let i = 0; i < digits.length; i++) {
    let square = Math.pow(digits, 2);
    console.log(square);
  }
};
digit(234);

output: NaN

digit = (num) => {
  let digits = String(num).split('').map(Number);

  for (let i = 0; i < digits.length; i++) {
    let square = Math.pow(digits[i], 2);
    console.log(square);
  }
};
digit(234);

output: 4 9 16

Is it possible to have my output as [4,9,16]?

What you want to do here is to modify the array in place, so you need to assign the result of Math.pow() to each element of the array.

 digit = (num) => { let digits = String(num).split("").map(Number); for(let i = 0; i < digits.length; i++) { digits[i] = Math.pow(digits[i], 2); } console.log(digits); }; digit(234);

After the for loop is done, then each array item will be squared.

Math.pow() expects two inputs, both of which should be numbers (not arrays)

You need to loop through your digits, and push the values to an array.

Something like this:

function digit(num) {
    let digits = String(num).split('')
    .map(Number);
    let square = [] // Define an empty array outside the loop
    for(let i = 0; i < digits.length; i++){
        square.push(Math.pow(digits[i],2)); //Push each value to the loop
    }
    return square; //Return the modified array after the loop
}

console.log(digit(234)); //Outputs [4, 9, 16]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM