在JavaScript中实现商品筛选功能,通常涉及以下几个基础概念:
假设我们有一个商品数组,每个商品有以下属性:name
, price
, category
。
const products = [
{ name: 'Laptop', price: 999, category: 'Electronics' },
{ name: 'Smartphone', price: 499, category: 'Electronics' },
{ name: 'Coffee Maker', price: 69, category: 'Home Appliance' }
];
// 单一条件筛选示例:筛选出所有电子产品
function filterByCategory(products, category) {
return products.filter(product => product.category === category);
}
const electronics = filterByCategory(products, 'Electronics');
console.log(electronics);
// 多条件组合筛选示例:筛选出价格低于500的电子产品
function filterProducts(products, filters) {
return products.filter(product => {
for (let key in filters) {
if (product[key] !== filters[key]) {
return false;
}
}
return true;
});
}
const filters = { category: 'Electronics', price: '<500' };
// 为了处理价格范围,我们需要稍微修改筛选逻辑
function filterProductsByPrice(products, maxPrice) {
return products.filter(product => product.price < maxPrice);
}
const affordableElectronics = filterProductsByPrice(products, 500);
console.log(affordableElectronics);
通过以上方法,你可以有效地实现并优化JavaScript中的商品筛选功能。
领取专属 10元无门槛券
手把手带您无忧上云