I am really new at learning JavaScript and I am completing some exercises from the Odin Project. I am stuck at one part of the calculator that should sum all the arguments, but the output changes if you use an array to call the function. My code is the following:
const sum = function(...numbers) {
let result = 0;
for (let each of numbers){
result += each};
return result;
};
It works perfect if I call the function like so:
sum(7,11) and it returns 18
However, one of the checks is that it needs to enter the arguments as an array:
test('computes the sum of an array of two numbers', () => { expect(calculator.sum([7,11])).toBe(18);
So when it calls the function like this sum([7,11]) it returns 07,11 and also returns it as a string, so it does not pass this check. I am pretty sure the solution may be simple but I am not able to find what the issue is.
const sum = function(...numbers) {
let result = 0;
for (let each of numbers){
result += each};
return result;
};
console.log(sum(7,11))
console.log(sum([7,11]))
>Solution :
The reason is that ...numbers means for array,and you have passing parameters like [7,11],so it’s a nested array,in this case,you need to use numbers[0] instead
You can reference to how-to-check-if-array-is-multidimensional-jquery to get more detail information of it.
const sum = function(...numbers) {
let result = 0;
let isSubArray = Array.isArray(numbers[0]);
let data = isSubArray ? numbers[0]:numbers;
for (let each of data){
result += each
};
return result;
};
console.log(sum([7,11]))
console.log(sum(7,11))