function that squares the values in an array

懵懂的女人 提交于 2021-01-24 11:44:49

问题


i've been instructed to create a function that takes values from an array and squares each value, and logging the numbers to the console. i've attempted two methods, neither of which work so far:

first attempt:

var numbers = [2, 7, 13, 24];

function squareAll(numbers) {
  var newArray = [];
  for(i = 0; i < numbers.length; i++) {
    numbers = newArray.push(Math.pow(numbers[i], 2))
    return newArray;
  }
  console.log(squareAll(numbers));
}

second attempt:

var numbers = [2, 7, 9, 25];
var newArray = [];
var squareAll = function(numbers) {
  for(var i = 0; i < numbers.length; i++){
    newArray = [];
    newArray.push(squareAll[i] * squareAll[i])
  };
  return newArray;
};
console.log(squareAll(newArray));

when i try both codes in the javascript console, both return undefined and won't give me a specific error so i'm unsure what's wrong here. any explanation would be appreciated!


回答1:


In your first attempt you are assigning a push method into a variable, which is a bad practice. Secondly, you are returning the function just right after the first cycle of the loop, so you are stopping the loop before going through all the elements of the array.

And in the second attempt, you are basically clearing the array after each cycle of the loop, because of the newArray = []; inside the loop. So with every cycle, you are dropping an element inside the newArray and then you are telling the loop to clear the newArray. The loop will become infinite, because the length of the newArray will never reach the numbers.length.

var numbers = [2, 7, 13, 24];
var newArray = [];

console.log(numbers.map(v => Math.pow(v, 2)));

Or:

var numbers = [2, 7, 13, 24];
var newArray = [];

for (var i = 0; i < numbers.length; i++) {
  newArray.push(Math.pow(numbers[i], 2));
}

console.log(newArray);



回答2:


Why not just use map

var result = [1,2,3,4,5].map(function(val){
  return Math.pow(val,2);
});

console.log(result); // [1, 4, 9, 16, 25]



回答3:


Use array.map() to set a callback function to be executed for each element in the array:

var arr1 = [1,2,3,4];

function squareIt(arr) {
  return arr.map(function (x) {
    return Math.pow(x, 2);
  });
}

alert(squareIt(arr1));


来源:https://stackoverflow.com/questions/39862347/function-that-squares-the-values-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!