国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Reply content:
Home Backend Development PHP Tutorial javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

Jul 06, 2016 pm 01:53 PM
css html html5 javascript php

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:

//全局對(duì)象
var item_arr = {};

//操作函數(shù)
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 ,強(qiáng)力免山寨


//模擬添加購(gòu)物操作
add_(19, "狗腿子", 16, 20);
add_(1, "雞腿子", 12, 2);
add_(126, "羊腿子", 6, 6);
add_(126, "羊腿子", 6, 6);


//輸出信息,計(jì)算價(jià)格
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("當(dāng)前有%s%d個(gè),總價(jià)%d元", item.name, item.count, price_curr);
}
console.info("共計(jì)%d元,祝您購(gòu)物愉快!", price_totle);

Output results
javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

How to create responsive images using CSS? How to create responsive images using CSS? Jul 15, 2025 am 01:10 AM

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Explain property inheritance in CSS Explain property inheritance in CSS Jul 15, 2025 am 01:25 AM

InCSS,propertyinheritanceaffectshowstylesarepassedfromparentelementstochildren.Somepropertieslikecolorandfont-familyinheritbydefault,applyingtoallnestedelementsunlessoverridden.Non-inheritedpropertiessuchasborder,margin,andpaddingmustbesetexplicitly.

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

Describe the `opacity` property Describe the `opacity` property Jul 15, 2025 am 01:23 AM

opacity is an attribute in CSS that controls the overall transparency of an element, with values ranging from 0 (fully transparent) to 1 (fully opaque). 1. It is often used for the image hover fade effect, and enhances the interactive experience by setting the opacity transition; 2. Making a background mask layer to improve text readability; 3. Visual feedback of control buttons or icons in the disabled state. Note that it affects all child elements, unlike rgba, which only affects the specified color part. Smooth animation can be achieved with transition, but frequent use may affect performance. It is recommended to use it in combination with will-change or transform. Rational application of opacity can enhance page hierarchy and interactivity, but it should avoid interfering with users.

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

See all articles