【问题标题】:How does modifying an array changes another array in JS修改一个数组如何改变JS中的另一个数组
【发布时间】:2021-09-03 22:47:44
【问题描述】:

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

下面的函数用于增加和减少订单的数量 using "+" and "-" buttons,如果action是“+”,则数量加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)
        }
    } 

【问题讨论】:

    标签: javascript arrays reactjs react-native react-hooks


    【解决方案1】:

    在 JS 中,当您将 对象类型 的值(例如对象字面量、数组、函数)分配给变量时,例如 x,基本上分配给 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)

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

    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)

    【讨论】:

    • 除此之外,filter() 仅将对象浅拷贝到新数组中。
    【解决方案2】:

    那是因为数组是非原始的。

    您需要将变量想象为值的连线。每个原始类型都是不可变的,因此当您尝试更改该变量的值时,您会更改它指向的“线”,这是另一个唯一值。 其他所有非原始值都是可变的,因此当您更改它的值时,指向该值的所有其他变量现在都将返回更改后的值。

    如果我这样做:

    const fruit = { name: 'apple' } // {} creates a new value and points to it
    const number = 1; // points to the primitive value 1
    

    如果我这样做:

    const anotherFruit = fruit;
    anotherFruit.name = 'banana'; // changes the value of fruit
    
    let anotherNumber = number;
    number = 3; // value 1 is a primitive, so it can't be changed, will point to value 3
    

    Dan Abramov 的一个小课程会让你更容易理解它:https://justjavascript.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多