/** * 深度比较两个对象是否相等 * @method compare * @param oldData 需要比较的值 * @param newData 需要比较的值 * @return {Boolean} 判断后的结果 */ export const compare = function (oldData, newData) { if (oldData === newData) return true; const arg = Array.prototype.slice.call(arguments); const objCall = (obj, string) => Object.prototype.toString.call(obj) === `[object ${string}]`; if (arg.every(obj => objCall(obj, 'Object')) && Object.keys(oldData).length === Object.keys(newData).length) { for (const key in oldData) { if (oldData.hasOwnProperty(key) && !compare(oldData[key], newData[key])) return false; } } else if (arg.every(obj => objCall(obj, 'Array')) && oldData.length === newData.length) { for (const key in oldData) { if (!compare(oldData[key], newData[key])) return false; } } else { return false; } return true; };
调用:
const obj = {};
const arr = [];
const result = compare(obj,arr); // false;
对象深度比较,简单又好吃;