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]?
CodePudding user response:
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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
After the for loop is done, then each array item will be squared.
CodePudding user response:
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]