如何对在"产品"中创建的产品进行排序上课并记录在" Shop"这个方法的本质在于按价格排序(能够设置顺序)sortByPrice(order)
console.log(shop.sortProductsByPrice(Product.SORT_ORDER_ASC));
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
//Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for sorting the product at its price
sortProductsByPrice(dataset, order, prop) {
let sorted = dataset.sort((a, b) => {
let innerA;
for (let subObjectName in a) {
let inner = a[subObjectName];
innerA = inner;
break;
}
let innerB;
for (let subObjectName in b) {
let inner = b[subObjectName];
innerB = inner;
break;
}
return order(innerA[prop], innerB[prop])
});
return sorted;
}
}
const shop = new Shop();
// create products
shop.addProduct(new Product("product 1", 1, 2000));
shop.addProduct(new Product("product 2", 1, 700));
shop.addProduct(new Product("product 3", 2, 800));
shop.addProduct(new Product("product 4", 3, 1000));
//sort by the specified key "price"
let res = shop.sortProductsByPrice(shop.products,
(a, b) => a - b, "price");
console.log(res);

答案 0 :(得分:1)
我在迭代中删除了for ...我不认为它正在做你的意思。
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
//Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for sorting the product at its price
sortProductsByPrice(dataset, order, prop) {
let sorted = dataset.sort((a, b) => {
return order(a[prop], b[prop])
});
return sorted;
}
}
const shop = new Shop();
// create products
shop.addProduct(new Product("product 1", 1, 2000));
shop.addProduct(new Product("product 2", 1, 700));
shop.addProduct(new Product("product 3", 2, 800));
shop.addProduct(new Product("product 4", 3, 1000));
//sort by the specified key "price"
let res = shop.sortProductsByPrice(shop.products,
(a, b) => a - b, "price");
console.log(res);