Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
- Write a function called sumNumbers that accepts a single array of numbers and returns the sum of the numbers in the array

I'm really new to JavaScript, So excuse me if this question might seem a little underwhelming.

I'm trying to write a function that performs the following:

1. accepts a single array of numbers and returns the sum of the numbers in the array. 2. If empty, returns 0.

let num3 = function sumNumbers([index]) {
if (index != "number") {
    return 0;
}
else {
    [index].reduce((a, b) => a + b, 0)
}


}



num3(1, 2, 3);

However, I am getting this error :

Uncaught TypeError: number 1 is not iterable (cannot read property Symbol(Symbol.iterator))
at sumNumbers (main.js:16:31)
at main.js:25:1

Anyone know the solution? would really appreciate it :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can iterate over the array using a for loop and increment the sum in each iteration and finally return it.

If there are no numbers in the array then the function would return the initial value of sum, which is 0.

function addNums(nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}

console.log(addNums([1, 2, 3]));
console.log(addNums([]));

You can also use Array.prototype.reduce and do the calculation in a single step.

const addNums = (nums) => nums.reduce((s, n) => s + n, 0);

console.log(addNums([1, 2, 3]));
console.log(addNums([]));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda