


javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !
Each product has an id, title, and price. Every time I click to buy, I add it to the array. However, I want to judge based on the Id. When adding a product to the shopping cart repeatedly, add the same product to an array. How to write a dimensional array?
<code>[ [ {鸡腿},{鸡腿},{鸡腿},{鸡腿} ], [ {狗腿},{狗腿},{狗腿} ], [ {猫咪},{猫咪},{猫咪},{猫咪},{猫咪},{猫咪} ] ] </code>
Thank you everyone, it’s true that my idea is really stupid, thank you for your suggestions!
Reply content:
Each product has an id, title, and price. Every time I click to buy, I add it to the array. However, I want to judge based on the Id. When adding a product to the shopping cart repeatedly, add the same product to an array. How to write a dimensional array?
<code>[ [ {鸡腿},{鸡腿},{鸡腿},{鸡腿} ], [ {狗腿},{狗腿},{狗腿} ], [ {猫咪},{猫咪},{猫咪},{猫咪},{猫咪},{猫咪} ] ] </code>
Thank you everyone, it’s true that my idea is really stupid, thank you for your suggestions!
The friend above is right, your idea is not advisable. Two-dimensional arrays are all the same thing. . A bit of a trap.
This format is better, please refer to it
<code>var cart = { 'id01':{n:'鸡腿', count: 4}, 'id02':{n:'鸭腿', count: 3}, 'id03':{n:'猪腿', count: 2}, 'id04':{n:'狗腿子', count: 1} } </code>
However, if you insist on doing it this way
<code>var list = [ [{n:'鸡腿'},{n:'鸡腿'},{n:'鸡腿'},{n:'鸡腿'},{n:'鸡腿'}], [{n:'鸭腿'},{n:'鸭腿'},{n:'鸭腿'},{n:'鸭腿'}], [{n:'猪腿'},{n:'猪腿'},{n:'猪腿'},{n:'猪腿'}] ]; function fn(o){ var inArray = false; list.map(function(item){ if( item.indexOf(o) > -1){ inArray = true; item.push(o); } }); inArray || list.push([o]); } fn(list[1][1]); fn({n:'狗腿子'}); </code>
This is just a reference and is not recommended
It is not recommended to write like this. The data structure of the shopping cart should store the product ID and quantity (assuming that the product ID here is the name)
<code>{ "鸡腿": 4, "狗腿": 3, "猫咪": 6 } </code>
In actual implementation, when adding or subtracting items in the shopping cart, you only need to add or subtract the following number
Your thinking is wrong. What you said above is correct. The main body of the shopping cart should be $a = ['id'=>number]
, then the price and name should be another array $b = ['id'=>['name'=>name,'price'=>price]]
, and the total price is $totalPrice = $a['id']*$b['id']['price']
I agree with the point above that the items in the shopping cart should be as a whole, but I personally feel that the price should not be stored in the shopping cart array, because the price when you add it and the price when you pay are not necessarily the same. What should be stored is the unique identifier id and quantity number. If you store title, price, if the merchant changes the name or price, how should your design be handled?
<code>$shoppingCart = [ '101' => 4,//鸡腿 '102' => 5,//狗腿 '103' => 6//鸭腿 ];</code>
First of all, thank you for the invitation.
Actually, I saw this question yesterday, and I think the answers above were pretty good. But seeing that the author of the question invited me again, I can only express my opinion as a way to attract others.
Actually, I think the number of dimensions of the array is not important. It is not important how to write it. What is important is the idea. I mainly want to make an introductory statement on this aspect.
In fact, in this day and age, although object-oriented is a commonplace thing, many people still don’t know how to use it, so the complexity of the problem has skyrocketed. Let’s try to use object-oriented to solve this problem:
//全局对象 var item_arr = {}; //操作函数 function add_(id, name, price, count) { var item = { id: id, name: name, price: price, count: count } var obj = item_arr[id] if (obj) { item.count = obj.count + count; } item_arr[item.id] = item; } //code by rozbo ,强力免山寨 //模拟添加购物操作 add_(19, "狗腿子", 16, 20); add_(1, "鸡腿子", 12, 2); add_(126, "羊腿子", 6, 6); add_(126, "羊腿子", 6, 6); //输出信息,计算价格 var price_totle = 0; for (var id in item_arr) { var item = item_arr[id]; var price_curr = item.count * item.price; price_totle += price_curr; console.info("当前有%s%d个,总价%d元", item.name, item.count, price_curr); } console.info("共计%d元,祝您购物愉快!", price_totle);
Output results

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
