如何用forEach实现数组对象间的属性值前值非空验证
数组属性非空校验(forEach实现)
需求说明
给定包含n个对象的数组,若当前索引对象的指定属性值为空,且下一个索引对象的同属性存在有效值时,抛出错误:前一个对象的该属性值不能为空。
示例测试数组:
const testArr = [{Id:1, name:'abc'}, {id:2, name:''}, {id:3, name:'dcg'}];
其中索引1的name为空,索引2的name有有效值,此时需触发错误提示。
实现代码
利用forEach遍历数组时的索引,直接获取下一个元素做对比校验:
const validateArrayProp = (arr, prop) => { arr.forEach((currentItem, index) => { // 跳过最后一个元素,无后续元素可对比 if (index === arr.length - 1) return; const nextItem = arr[index + 1]; // 这里的空值判断可根据实际场景调整(比如区分null/undefined/空字符串) const currentPropIsEmpty = !currentItem[prop]; const nextPropHasValue = !!nextItem[prop]; if (currentPropIsEmpty && nextPropHasValue) { throw new Error('前一个对象的该属性值不能为空'); } }); }; // 执行校验 try { validateArrayProp(testArr, 'name'); } catch (err) { console.error(err.message); // 输出:前一个对象的该属性值不能为空 }
注意事项
- 遍历中跳过最后一个元素,避免数组越界访问
- 空值判断逻辑可按需扩展:比如需要严格匹配空字符串,可改为
currentItem[prop] === '',若要包含null/undefined,则调整为currentItem[prop] == null || currentItem[prop] === '' - 必须用
try/catch包裹校验逻辑,否则抛出的错误会终止程序运行
内容的提问来源于stack exchange,提问作者Anusha
相关产品推荐
相关产品推荐

