简体   繁体   中英

Can't get data from JavaScript array

I have this code

var obj = [];
$('#next').click(function(){
  jQuery.getJSON(produk1 , function(product1) {
    hargana1 = product1.price;
    obj.push({
       harga: hargana1
    });
  }

  jQuery.getJSON(produk2 , function(product1) {
    hargana2 = product2.price;
    obj.push({
       harga: hargana2
    });
  }

  console.log(harga)
});

And I have result on my console like this

安慰

How can I get value from harga? I try with obj['harga'] It shows undefined

Well if you take a closer look then you will see that this is actually an array filled with objects. you can see that its an array by the brackets []

Try it like this: obj[0].harga

You should iterate through the array:

 const out = [{harga:21132424},{harga:543535}] console.log(out) out.forEach(obj=>{ const harga = obj.harga; //do something to harga here console.log(harga) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM