首页 > 解决方案 > 修改一个数组如何改变JS中的另一个数组

问题描述

我希望有人帮助我了解更改项目数组如何更改下面函数中的orderList数组?

下面的函数用于使用“+”和“-”按钮增加和减少订单的数量 ,如果操作是“+”,则数量加 1,否则数量减 1

        const [orderItems, setOrderItems] = React.useState([])

        const editOrder = (action, menuId, price) => {

        let orderList = orderItems.slice() 
        let item = orderList.filter(a => a.menuId == menuId)

        if(action == "+"){
            if(item.length > 0)
                let newQty = item[0].qty + 1
                item[0].qty = newQty
                item[0].total = item[0] * price
            } else {
                const newItem = {
                    menuId: menuId,
                    qty: 1,
                    price: price,
                    total: price
                }
                orderList.push(newItem)
            }
            setOrderItems(orderList)
        } else {
            if(item.length > 0) {
                if (item[0].qty > 0){
                    let newQty = item[0].qty - 1
                    item[0].qty = newQty
                    item[0].total = newQty * price
                }
            }
            setOrderItems(orderList)
        }
    } 

标签: javascriptarraysreactjsreact-nativereact-hooks

解决方案


在 JS 中,当您将对象类型的值(例如对象文字、数组、函数)分配给变量 sayx时,基本上分配给x的是对原始值的引用。

如果我有

let a = {a: 123}; // _a_ is object
let b = a; // Now _b_ has a reference to it
b.a = 312; // Essentially here we are modifying _a_
console.log(a.a)

您会看到我们设法a通过b. 数组也会发生同样的事情;

let a = [{a: 123}]; // Array is also object type
let b = a; // Same logic applies here, _b_ points to _a_ basically
b[0].a = 312;
console.log(a[0].a)


推荐阅读