arrays - 如何使 ColdFusion 数组中的项目独一无二?
解决方案
为了确保您的购物车对于每篇文章始终只有一个位置,我将使用结构而不是数组来让您的购物车中的每篇文章始终拥有一个位置,并避免使用同一篇文章的多个副本填充它。
通过为您的购物车使用结构,您可以创建一个结构键(例如,带有文章 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>
推荐阅读
- c++ - 使用 std::condition_variable 触发其他线程。使用哪些互斥锁?
- javascript - 在初始化之前使用变量。JS
- javascript - 初始搜索后无法再次搜索
- prolog - 比较二叉树 SWI Prolog 中的节点
- python - 如何递归地抓取网页以检查python中是否有新的pdf文件?
- c++ - 如何使用 libcurl 将图像上传到 Twitter?
- mysql - Node JS, Express MySQL ES_PARSE_ERROR...“在'?,?,?,?,?附近使用正确的语法”
- reactjs - 子组件不会通过更改道具来更新
- mysql - 即使使用错误的凭据也能成功登录?
- groovy - 在 JMeter 的 JSR223 断言中获取所有以前的采样器结果(重定向)