[英]Javascript change property inside object within array logic
case ActionTypes.ADD_TO_CART: {
var newOrders = state.cartItems.slice();
let updatedIem = state.cartItems.find(i => {
if (i.id === action.product.id) {
return action.product
}
else {
return null
}
});
if (updatedIem) {
var oldOrder = newOrders[action.itemIndex];
var newOrder = Object.assign({}, oldOrder);
if (action.direction == 1 && newOrder.quantity > 0) {
newOrder.qty++;
newOrder.quantity--;
}
else if (action.direction == -1 && newOrder.qty != 0 && newOrder.quantity > 0) {
newOrder.qty--;
newOrder.quantity++;
}
else null
newOrders[action.itemIndex] = newOrder;
}
else {
newOrders[action.itemIndex] = action.product
}
return {
...state,
cartItems: newOrders,
};
}
This code returns an Array cartItems
in the returned object but the problem is that one of Array elements is undefined
, as in: [{first object}, undefined, {third object}]
.此代码在返回的cartItems
但问题是其中一个数组元素是undefined
,如: [{first object}, undefined, {third object}]
。
The undefined
element is not wanted.不需要undefined
的元素。 I know it's coming from one of the assignments to newOrders[action.itemIndex]
but I don't know how to track this down.我知道它来自对newOrders[action.itemIndex]
的一项分配,但我不知道如何追踪它。
I see two ways to approach this problem:我看到了两种解决这个问题的方法:
(1) Make sure that you are not inserting undefined
objects into your array. (1) 确保您没有将undefined
的对象插入到数组中。 You can do this with a simple (object == null)
check.您可以通过简单的(object == null)
检查来做到这一点。 This will capture null and undefined objects.这将捕获 null 和未定义的对象。
(2) Filter out undefined objects, eg cartArray = cartArray.filter(item => item != null)
. (2) 过滤掉未定义的对象,例如cartArray = cartArray.filter(item => item != null)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.