简体   繁体   中英

Javascript putting object inside arrays

I'm having some troubles using Javascript. I have a list of bottles (more than a 100) and each of those have different specifities (price, name,alchool, etc). I wish to make a simple and organized "database " per say.

Maybe if I show this you would understand the gist of what I'm trying to do.

 var tequila = [{name:"José",price:16.35,concen:"38",alctype:"blanco", quant:0}, {name:"El Jimador",price:22.45,concen:38,alctype:"blanco", quant:0}, {name:"Gran Centenario Plata Tequila",price:29.75,concen:38,alctype:"blanco", quant:0}, {name:"1800 Silver",price:31.25,concen:38,alctype:"blanco", quant:0}, {name:"Herradura",price:37.45,concen:38,alctype:"blanco", quant:0} ] document.getElementById("fafa").innerHTML = tequila[3].price; 
 <p id="fafa"></p> 

By doing this doc-get-element tequila[3].price I wish to access the price of the the third bottle in the list.

Unfortunately it doesn't work. I have been searching around and I couldn't find a person who's had this similar issue. Is the syntax wrong? Or does this feature not exist in Javascript?

Thank you for your time, I appreciate any tips and pointers you could give me.

The code works well. Just make sure that the tequila has array type instead of string otherwise you need to do JSON.parse(tequila) before accessing the value.

 var tequila = [{name:"José",price:16.35,concen:"38",alctype:"blanco", quant:0}, {name:"El Jimador",price:22.45,concen:38,alctype:"blanco", quant:0}, {name:"Gran Centenario Plata Tequila",price:29.75,concen:38,alctype:"blanco", quant:0}, {name:"1800 Silver",price:31.25,concen:38,alctype:"blanco", quant:0}, {name:"Herradura",price:37.45,concen:38,alctype:"blanco", quant:0} ] document.getElementById("fafa").innerHTML = tequila[3].price; 
 <p id="fafa"></p> 

由于数组索引从0开始。那么您应该执行tequila[2].price以获取第三瓶价格。

这是一个错字,您错把价格弄错了

尝试这样使用

Object(tequila[3].price)

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