Object with functions. Challenge
-
Help me meet this challenge. Here's the condition: Make an object with three functions, each of which will accept the size range. Make sure that the first function returns the sum of the mass, the second function is the sum of squares and the third is the amount of the cubs. But I'm doing something wrong, I don't understand.
My decision is:
let math = { sum: function(arr) { return sum += elem }, square: function(arr) { return elem * elem }, cube: function(arr) { return elem * elem * elem }, }; let arr = [1, 2, 3, 4, 5]; for (let elem of arr) { arr[elem]; } alert(math.sum([1, 2, 3, 4, 5])); alert(math.square([1, 2, 3, 4, 5])); alert(math.cube([1, 2, 3, 4, 5]));
-
A method is good for adding the mass. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce ♪ You don't have to multiply the variable on you a bunch of times. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation (and in ancient times when we didn't use it) https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/pow )
const math = { sum(arr) { return arr.reduce((sum, elem) => sum + elem, 0); }, square(arr) { return arr.reduce((sum, elem) => sum + elem ** 2, 0); }, cube(arr) { return arr.reduce((sum, elem) => sum + elem ** 3, 0); }, }; console.log(math.sum([1, 2, 3, 4, 5])); console.log(math.square([1, 2, 3, 4, 5])); console.log(math.cube([1, 2, 3, 4, 5]));