使用 `switch` 替换条件语句的示例

2024-10-16

情景:管理用户选择的购物车

想象一下,你正在设计一个电子商务网站上的购物车应用程序。你的目标是实现一个功能,允许用户在添加商品到购物车后可以轻松地更改他们的决定。例如,如果用户花费了 $20 的金额并添加了 3 个这种产品,那么删除其中一个将使总费用从 $60 节约到 $57。

情景解释

当用户点击“移除”按钮时,这项事件需要被处理来检查他们所选择的项目,并如果它是在你的购物车中,则减少总价。为了实现这一点,JavaScript 的 switch 语句可以作为一种替代传统的条件语句。

示例场景

假设你有一个产品列表:

const products = [
    { name: 'Product A', price: 20, quantity: 3 },
    { name: 'Product B', price: 15, quantity: 2 }
];

现在,让我们设计一个函数,允许用户删除购物车中的一个项目:

function updateCart(cartItems, productToRemove) {
    const index = cartItems.findIndex(item => item.name === productToRemove);
    
    if (index !== -1) {
        // 删除所选产品的单个实例。
        cartItems.splice(index, 1);
        return cartItems;
    } else {
        console.log(`${productToRemove} 不在你的购物车中。`);
        return [];
    }
}

// 示例使用:
const updatedCart = updateCart(products, 'Product A');
console.log(updatedCart); // 输出:[{ name: 'Product B', price: 15, quantity: 2 }]

使用 switch 语句的解释

在 JavaScript 中,当条件数量有限且确定时,使用 switch 语句可以将复杂的选择逻辑压缩到单行代码中。特别是在处理多个选择情况而只需少量可能的情况时非常有用。

在我们的购物车示例中,每个产品都有不同的属性(价格和数量),所以我们需要通过数组索引来检查要删除的项目。当删除一个项目时,像上述 remove 函数那样从列表中删除单个实例是完全一样的。

使用 switch 语句为什么更好?

  1. 可读性:决定应采取什么行动的逻辑清晰且容易理解,对于其他人(甚至是你自己)来说也是如此。
  2. 简明性:将复杂的条件语句压缩到简单的比较中,使代码更简洁。
  3. 维护性:如果未来某些情况下这个函数应该被执行的条件发生变化,更新一个地方会比在多个地方重复相同逻辑要容易。

总结

当有有限的选择项但可能的情况较少时,switch 语句是一个处理多种情况的有效工具。不论你在你的应用程序中实现这种功能时是否有其他需求和偏好,掌握这些 JavaScript 基础知识会使代码更有效、更易读! Sure! Below is an example of how you can implement the shopping cart functionality using both switch and traditional conditional statements (if-else), followed by a comparison.

Traditional If-Else Statements

function updateCart(cartItems, productToRemove) {
    let updatedCart = [];

    for(let i = 0; i < cartItems.length; i++) {
        if (cartItems[i].name !== productToRemove) {
            updatedCart.push(cartItems[i]);
        }
    }

    return updatedCart;
}

// 示例使用:
const updatedCart = updateCart(products, 'Product A');
console.log(updatedCart); // 输出:[ { name: 'Product B', price: 15, quantity: 2 }]

Using Switch Statements

function updateCart(cartItems, productToRemove) {
    let index;
    const newCart = [];

    switch (true) {
        case cartItems.length > 0:
            for(let i = 0; i < cartItems.length; i++) {
                if (cartItems[i].name !== productToRemove) {
                    newCart.push(cartItems[i]);
                }
            }
            return newCart;
        default:
            console.log(`${productToRemove} 不在你的购物车中。`);
    }
}

// 示例使用:
const updatedCart = updateCart(products, 'Product A');
console.log(updatedCart); // 输出:[ { name: 'Product B', price: 15, quantity: 2 }]

Using Switch Statements with Array Index

function updateCart(cartItems, productToRemove) {
    let index;
    const newCart = [];

    switch (true) {
        case cartItems.length > 0:
            for(let i = 0; i < cartItems.length; i++) {
                if (cartItems[i].name === productToRemove) {
                    index = i;
                }
            }

            if (index !== -1) {
                newCart.push(...cartItems.slice(0, index), ...cartItems.slice(index + 1));
                return [...new Set(newCart)];
            } else {
                console.log(`${productToRemove} 不在你的购物车中。`);
                return [];
            }
        default:
            break;
    }

    return cartItems;
}

// 示例使用:
const updatedCart = updateCart(products, 'Product A');
console.log(updatedCart); // 输出:[ { name: 'Product B', price: 15, quantity: 2 }]

总结

Both the traditional if-else statements and the switch statement can achieve the same result. However, a switch statement is more concise when dealing with fewer cases or limited choices.

In summary:

function updateCart(cartItems, productToRemove) {
    const newCart = [];

    switch (true) {
        case cartItems.length > 0:
            for(let i = 0; i < cartItems.length; i++) {
                if (cartItems[i].name === productToRemove) {
                    newCart.push(...cartItems.slice(0, i), ...cartItems.slice(i + 1));
                    return [...new Set(newCart)];
                }
            }
            break;
        default:
            console.log(`${productToRemove} 不在你的购物车中。`);
    }

    return cartItems;
}

// 示例使用:
const updatedCart = updateCart(products, 'Product A');
console.log(updatedCart); // 输出:[ { name: 'Product B', price: 15, quantity: 2 }]

This function removes the product from the cart by iterating over the array and skipping it in the switch statement. This approach simplifies the logic without needing to maintain a separate list or index variable.

Blog Post Image