Nan error in object array

Asked

Viewed 26 times

1

var armazenamento = [];
armazenamento.push({nome: nomeproduto, valor: + preco})
for(i in armazenamento){
   total =+ armazenamento[valor: i]
   i++
   }
console.log(total)
troco = PagoCliente - total

I created an array called storage and added name and value to it, then I’m trying to store all the values in a variable called total to then display how much change to give to the client. Only when I ask for change he’s showing up Nan

  • Romulo, is your example running? For this line total =+ armazenamento[] nor does it allow me to execute the code.

  • ended that I did not put here, but it was to come out like this: total =+ storage[{value: i}]

2 answers

2


Replace your for in by a for of:

for (let i of armazenamento) {
   total =+ i.valor;
}

The for in iterates over the properties of an object, while the for of iterates on a array, map etc... And as its variable armazenamento is an array, the for of solves your problem.

See more about these for in the documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in


Your complete code will look like this (I declared some variables to work):

//Variáveis declaradas para efeitos de teste
let total = 0;
let PagoCliente = 69;
let nomeproduto = "Xisto";
let preco = 13;

var armazenamento = [];

armazenamento.push({nome: nomeproduto, valor: + preco});

for (let i of armazenamento) {
   total =+ i.valor;
}

console.log(total);

troco = PagoCliente - total;

console.log(troco);

  • 1

    I think yours is better than mine :)

2

You can also use the method reduce() to do what you want, it is very indicated when we need to manipulate values in arrays:

var armazenamento = [];
var PagoCliente = 50;
var troco;

armazenamento.push({
  nome: 'produto 01',
  valor: 10
})

armazenamento.push({
  nome: 'produto 02',
  valor: 5
})

var total = armazenamento.reduce((anterior, atual) => {
    return anterior + atual.valor;
},0)

troco = PagoCliente - total;

console.log('Total: ', total);
console.log('Troco: ', troco);

  • Good! I forgot this example :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.