JS代码:
//定义数据集合 const persons =[ { id: 1, name: '张三'}, { id: 2, name: '李四'} ] console.log('') console.log('初始化数据为:', JSON.stringify(persons)) console.log('') //--------- 设定场景1 -> 新增时存在相同姓名 --------- console.log('-------------------场景1-------------------') //新增状态id为-1,验证后重新在前端生成一个id,或者由后台生成 let person1 = { id: -1, name: '张三'} //验证 let verifyObj1 = persons.find(item => item.name === person1.name &&item.id !==person1.id) //如果找到相同对象,则不允许添加 if(verifyObj1) { console.log('存在相同姓名,新增失败') console.log('场景1结果:', JSON.stringify(persons)) } else{ //通过验证,允许新增 persons.push(person1) console.log('场景1结果:', JSON.stringify(persons)) } console.log('-------------------场景1-------------------') console.log('') //--------- 设定场景2 -> 新增时不存在相同姓名 --------- console.log('-------------------场景2-------------------') //新增状态id为-1,验证后重新在前端生成一个id,或者由后台生成 person1 = { id: -1, name: '马六'} //验证 verifyObj1 = persons.find(item => item.name === person1.name &&item.id !==person1.id) //如果找到相同对象,则不允许添加 if(verifyObj1) { console.log('存在相同姓名,新增失败') console.log('场景2结果:', JSON.stringify(persons)) } else{ person1.id = persons.length + 1 //ID自增 //通过验证,允许新增 persons.push(person1) console.log('场景2结果:', JSON.stringify(persons)) } console.log('-------------------场景2-------------------') console.log('') //--------- 设定场景3 -> 编辑时存在相同姓名 --------- console.log('-------------------场景3-------------------') //编辑状态id为实际的编辑对象id let personIndex = 0 //假设编辑张三 let person2 =persons[personIndex] person2.name = '李四' //验证 let verifyObj2 = persons.find(item => item.name === person2.name &&item.id !==person2.id) //如果找到相同对象,则不允许修改 if(verifyObj2) { console.log('存在相同姓名,修改失败') console.log('场景3结果:', JSON.stringify(persons)) } else{ //通过验证,允许修改 persons[personIndex] =person2 console.log('场景3结果:', JSON.stringify(persons)) } console.log('-------------------场景3-------------------') console.log('') //--------- 设定场景4 -> 编辑时不存在相同姓名 --------- console.log('-------------------场景4-------------------') //编辑状态id为实际的编辑对象id personIndex = 0 //假设编辑张三 person2 =persons[personIndex] person2.name = '王五' //验证 verifyObj2 = persons.find(item => item.name === person2.name &&item.id !==person2.id) //如果找到相同对象,则不允许修改 if(verifyObj2) { console.log('存在相同姓名,修改失败') console.log('场景4结果:', JSON.stringify(persons)) } else{ //通过验证,允许修改 persons[personIndex] =person2 console.log('场景4结果:', JSON.stringify(persons)) } console.log('-------------------场景4-------------------') console.log('')
运行结果: