0

I can't print any item from the array "valores". I don't know what's happening. Am I doing a sintaxis error?. When I do a console.log(valores.length) results 0.

var valores = new Array();

fetch("https://mindicador.cl/api")
.then (data => data.json())
.then (data => {
    valores["dolar"] = data.dolar.valor;
    valores["euro"] = data.euro.valor;
    valores["utm"] = data.utm.valor;
    valores["uf"] = data.uf.valor;
});

for (var index in valores){
    document.write(valores[index]+"<br>");
}
Andreas
  • 21,535
  • 7
  • 47
  • 56
n21b
  • 43
  • 1
  • 4
  • The given code never defines `valores` - where and how do you define it? Also: `fetch()` is an asynchronous operation, so in the above code the `for` loop will be executed before any of the `then()` callbacks after `fetch()`. – Sirko Oct 01 '18 at 14:15
  • 2
    `valores` should be an object (`{}`) instead of an array (`[]`) – Andreas Oct 01 '18 at 14:17

2 Answers2

5

Your problem is time. You are making a promise to a server requesting information and filling valores array. But the problem is you're executing your for loop right after:

for (var index in valores){
    document.write(valores[index]+"<br>");
}

You need to to handle your document.write inside then method

.then (data => {
    valores["dolar"] = data.dolar.valor;
    valores["euro"] = data.euro.valor;
    valores["utm"] = data.utm.valor;
    valores["uf"] = data.uf.valor;
    for (var index in valores){
        document.write(valores[index]+"<br>");
    }
});
César Ferreira
  • 681
  • 1
  • 5
  • 12
2

I think you're having a misunderstanding of what an Array does. Try using an object instead of an array:

var valores = new Object();
fetch("https://mindicador.cl/api")
.then (data => data.json())
.then (data => {
    valores["dolar"] = data.dolar.valor;
    valores["euro"] = data.euro.valor;
    valores["utm"] = data.utm.valor;
    valores["uf"] = data.uf.valor;

    for (var key in Object.keys(valores)){
        document.write(valores[key]+"<br>");
    }

});

Let me know if you want more explanation. I'd be happy to elaborate.

Edit: it's worth noting that as others have pointed out, your are not obeying the callbacks for you data either.

Peter Van Drunen
  • 543
  • 5
  • 15