问题描述
我有一个正在向结帐页面添加产品的购物车。 如您所见,购物车的结构是这样设置的:
问题是,我只希望出现唯一值,没有重复。不知道如何使数组严格,使其只包含唯一值。
解决方法
为了确保您的购物车始终只有每件商品的一个位置,我会使用结构体而不是数组来让您购物车中的每件商品始终拥有一个位置,并避免将同一件商品的多个副本填充到其中。
通过为您的购物车使用结构体,您可以创建一个结构体键(例如使用商品 ID),它也是购物车中唯一商品的唯一引用。如果您使用数组,则只有数字,并且您需要深入查看数据结构以验证该商品是否已存在于购物车中。
这里只是一个简单的例子,说明我将如何使用数据结构。我没有添加诸如添加/删除单个文章单元之类的功能。这只是一个示例,说明我将如何处理购物车数据结构以使用唯一键引用它,以便可以快速访问和进一步操作。
<cfscript>
// function to add an article structure to the cart
function addArticleToCart(struct articleCartData required) {
// If the article is not present in the cart,add it as a struct to the cart wirh it's own articleID as the cart struct key:
If(!structKeyExists(cart,arguments.articleCartData.articleID)) {
cart.append({
"#arguments.articleCartData.articleID#": arguments.articleCartData
});
} else {
// Add the quantity of the cart by one unit
cart[arguments.articleCartData.articleID].quantity++
};
};
//Define empty cart
cart = {};
//Define the article that will be added to the cart
articleToAdd = {
articleID: "ART12345",articleName: "5650R Sheerweave Oyster",quantity: 1,unitPrice: 12.99
};
// Call the function to add the article to the cart
addArticleToCart(
articleToAdd
);
writedump(cart);
addArticleToCart(
articleToAdd
);
writedump(cart);
addArticleToCart(
articleToAdd
);
writedump(cart);
</cfscript>
,
这是一种如何使数组项唯一的解决方案。
代码
<cfscript>
cart = [
{
title: "foo"
},{
title: "bar"
},{
title: "foo"
},{
title: "bar"
}
];
function makeItemsUnique(array,property) {
return arrayReduce(array,function(reducedArray,item) {
if (not arraySome(reducedArray,function(uniqueItem) { return uniqueItem[property] eq item[property]})) {
arrayAppend(reducedArray,item);
}
return reducedArray;
},[]);
}
writedump(makeItemsUnique(cart,"title"));
</cfscript>
输出
说明
函数 makeItemsUnique()
负责使购物车中的商品独一无二。允许它处理不同类型的结构数组是通用的。使用购物车数组和用于过滤它的属性名称调用它。
在该函数中,对 arrayReduce()
的调用将数组缩减为仅包含唯一项的新数组。它通过检查新数组中是否已经有一个具有相同标题的项目来实现。此检查使用 arraySome()
完成。如果新数组不包含具有该标题的元素,则通过 arrayAppend()
添加。