React中检查tableRows数组对象是否至少一个属性值≥100000及优化
问题描述
我有一个名为tableRows的对象数组,具体结构如下:
tableRows = [ { purchase_sales:1000, yearFirstRemAmount: 1456, capitalServicePurchase:123234, otherServicePurchase: 12323, otherStuffPurchase: 8903, capitaStuffPurchase: 1200, currentYearServiceSell: 47856, currentYearStuffSell: 100000, yearLastRemAmount: 20000 }, { purchase_sales:23430, yearFirstRemAmount: 12500, capitalServicePurchase: 1000010, otherServicePurchase: 12360, otherStuffPurchase: 12300, capitaStuffPurchase: 12000, currentYearServiceSell: 123123, currentYearStuffSell: 12111, yearLastRemAmount: 13120 } ]
我需要检查数组中指定索引对应的对象的9个键值对里,是否至少有一个值大于等于100000。但我编写的代码无法正常工作:
const handleValidation = (index)=>{ if(tableRows[index].purchase_sales<100000 || tableRows[index].yearFirstRemAmount<100000 || tableRows[index].capitalServicePurchase<100000 || tableRows[index].otherServicePurchase<100000 || tableRows[index].otherStuffPurchase<100000 || tableRows[index].capitaStuffPurchase<100000 || tableRows[index].currentYearServiceSell<100000 || tableRows[index].currentYearStuffSell<100000 || tableRows[index].yearLastRemAmount<100000 ){ alert("'At least one amount should be greater than or equal to 100000!!!") } }
请问是否有更简洁高效的方式实现该需求?
解决方案
1. 修正原代码的逻辑错误
你的代码逻辑存在问题:使用||时,只要有一个值小于100000就会触发弹窗,但实际需求是所有值都小于100000时才需要提示。只需将||替换为&&即可修复:
const handleValidation = (index)=>{ const row = tableRows[index]; if(row.purchase_sales < 100000 && row.yearFirstRemAmount < 100000 && row.capitalServicePurchase < 100000 && row.otherServicePurchase < 100000 && row.otherStuffPurchase < 100000 && row.capitaStuffPurchase < 100000 && row.currentYearServiceSell < 100000 && row.currentYearStuffSell < 100000 && row.yearLastRemAmount < 100000){ alert("At least one amount should be greater than or equal to 100000!!!"); } }
2. 更简洁高效的实现方式
利用Object.values()提取对象的所有值,结合Array.some()方法判断是否存在至少一个值满足>=100000的条件。如果不存在(即所有值都小于100000),则触发提示:
const handleValidation = (index)=>{ const row = tableRows[index]; const hasValidValue = Object.values(row).some(value => value >= 100000); if(!hasValidValue){ alert("At least one amount should be greater than or equal to 100000!!!"); } }
这种写法的优势:
- 代码精简,无需重复编写多个判断条件
- 扩展性强,后续对象的键新增或删除时,代码无需修改
- 语义清晰,
some()方法直接表达了“是否存在至少一个符合条件的元素”的逻辑
内容的提问来源于stack exchange,提问作者P_99
相关产品推荐
相关产品推荐

