循环检查 selinfo 数组中的每一个对象,判断其中的 po_qty 和 price 是否为空(null、undefined 或空字符串 ""),可以使用以下几种方法:
方法1:使用 forEach 循环检查每一项
const selinfo = this.data.selinfo;selinfo.forEach((item, index) => {if (!item.po_qty || !item.price) {console.log(`第 ${index + 1} 项数据不完整:`, item);// 可以在这里处理不符合条件的数据}
});
判断逻辑
-
!item.po_qty→ 检查po_qty是否为null、undefined、0或"" -
!item.price→ 检查price是否为null、undefined、0或""
如果你希望 严格判断空值(仅 null 或 undefined),可以改成:
if (item.po_qty == null || item.price == null) {console.log(`第 ${index + 1} 项数据为空:`, item);
}
方法2:使用 some() 检查是否有任意一项为空
const hasEmptyData = selinfo.some(item => !item.po_qty || !item.price);if (hasEmptyData) {console.log("存在数据不完整的项");
} else {console.log("所有数据完整");
}
方法3:使用 filter() 获取所有不完整的数据
const incompleteItems = selinfo.filter(item => !item.po_qty || !item.price);if (incompleteItems.length > 0) {console.log("以下数据不完整:", incompleteItems);
} else {console.log("所有数据完整");
}
方法4:使用 map() 返回检查结果
const checkResults = selinfo.map(item => ({...item,isValid: item.po_qty != null && item.price != null,
}));console.log("检查结果:", checkResults);
输出示例:
[{ id: 1, po_qty: 10, price: 100, isValid: true },{ id: 2, po_qty: null, price: 50, isValid: false },{ id: 3, po_qty: 5, price: null, isValid: false }
]
严格判断空值(排除 0 和 "")
如果 po_qty 或 price 可能是 0 或空字符串 "",但你仍然希望它们是有效值,可以这样判断:
const isInvalid = (value) => value === null || value === undefined;selinfo.forEach(item => {if (isInvalid(item.po_qty) || isInvalid(item.price)) {console.log("该项数据不合法:", item);}
});
扩展
判断数据项中某两项的数据和另一项的数据比
判断selinfo数组中,子项now_qty与reject_qty的和是否小于inv_qty
const isRowValid = selinfo.every(row =>(row.now_qty || 0) + (row.reject_qty || 0) <= (row.inv_qty || 0)
);
if (!isRowValid) {wx.showToast({title: '输入数量请小于库存量!',icon: 'none'});return;
}
总结
| 方法 | 适用场景 | 返回值 | 推荐度 |
|---|---|---|---|
forEach | 遍历并检查每一项 | 无返回值,可执行操作 | ✅ 推荐 |
some | 只想知道是否有空数据 | true / false | ✅ |
filter | 获取所有不完整的数据 | 数组 | ⚠️ 适用于需要具体数据时 |
map | 返回检查结果 | 新数组 | ⚠️ 适用于需要标记数据时 |
推荐方案
-
如果只是检查是否有空数据 →
some() -
如果需要获取哪些数据为空 →
filter() -
如果需要遍历并处理空数据 →
forEach