[英]javascript - array with key/value pairs
是否可以在 javascript 中的 arrays 中有一個鍵值對。 我正在尋找類似以下的東西
const array =
[
'item': 'Jumper', 'price', '160',
'item': 'Shirt', 'price', '50',
'item': 'Cap', 'price', '20',
]
還是有更好的數據結構可以使用?
是的,您只需將其設為對象數組:
const array = [ {'item': 'Jumper', 'price': '160'}, {'item': 'Shirt', 'price': '50'}, {'item': 'Cap', 'price': '20'}, ] console.log(array);
使用對象。 您可以按照@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.