javascript - 修改一个数组如何改变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)
}
}
解决方案
在 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)
推荐阅读
- docker - 在 RHEL 容器中安装“en_US”
- hadoop - hadoop v 2如何处理namenode的失败
- hibernate - 如何在休眠中删除子对象之前打破父子关系?
- css - 为什么 _partial 包含在 sass 中
- plugins - 使用 Apache Drill 从 Hive 访问表时出错
- java - Logback 不记录 JUL 精细级别
- grails - 类 [com.docu.MemberInfo] 上的方法在 Grails 应用程序之外使用
- android - 谷歌地图 v2 渲染问题
- matlab - 如何遍历表的一列并将其写入 csv 文件
- python - 芹菜组和链