/** * 堆代码 duidaima.com * originList数组中追加newList数组 * @param {Object} originList 原数组 * @param {Object} newList 需要添加的数组 * @param {Object} id 判断的值 * 数组去重方法 */ handleRemoveRepeat(originList, newList, id) { if (originList.length === 0 || newList.length === 0) return; let tag = 2; /* 0:不反转,1:反转 , 2:直接返回(证明没有重复的数据)*/ for (let i = 0; i < originList.length; i++) { /* 判断第一条数据是否在原有数组中,需要标记,不反转新数组 */ if (newList[0][id] === originList[i][id]) { tag = 0; break; } /* 判断最后一条数据是否在数组中 需要标记,反转新数组,最后还需要反转回来*/ if (newList[newList.length - 1][id] === originList[i][id]) { tag = 1; break; } } if (tag === 2) return; if (tag === 1) newList.reverse(); for (let i = 0; i < newList.length; i++) { let originListLength = originList.length; while (originListLength--) { /* 删除相同的数据 */ if (newList[i][id] === originList[originListLength][id]) { originList.splice(originListLength, 1); break; } } // 如果存在有数据不重复直接就退出遍历 if (originListLength + 1 === 0 && newList[i][id] !== originList[originListLength + 1][id]) return; } if (tag === 1) newList.reverse(); }解释两处地方:
3. tag=2 ,没有重复数据,直接返回(不考虑中间有相同数据的情况)