[英]javascript - array with key/value pairs
Is it possible to have a key value pair in arrays in javascript.是否可以在 javascript 中的 arrays 中有一个键值对。 I'm looking to have something like the following
我正在寻找类似以下的东西
const array =
[
'item': 'Jumper', 'price', '160',
'item': 'Shirt', 'price', '50',
'item': 'Cap', 'price', '20',
]
Or is there a better datastructure to use?还是有更好的数据结构可以使用?
Yes, you just make it an array of objects:是的,您只需将其设为对象数组:
const array = [ {'item': 'Jumper', 'price': '160'}, {'item': 'Shirt', 'price': '50'}, {'item': 'Cap', 'price': '20'}, ] console.log(array);
Use objects.使用对象。 You can do it the way it's shown in @dave's answer, or you can instead use classes :
您可以按照@dave 的答案中显示的方式进行操作,也可以改用classes :
class Product {
constructor(item, price) {
this.item = item;
this.price = price;
}
}
const array = [
new Product('Jumper', 160),
new Product('Shirt', 50),
new Product('Cap', 20),
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.