深度比较
function isObject(obj) { return typeof obj === 'object' && obj !== null } function isEqual(obj1, obj2) { if (!isObject(obj1) || !isObject(obj2)) { return obj1 === obj2; } if (obj1 === obj2) { return true; } let obj1keys = Object.keys(obj1); let obj2keys = Object.keys(obj2); if (obj1keys.length !== obj2keys.length) { return false; } for(let k in obj1) { const res = isEqual(obj1[k], obj2[k]); if (!res) { return false } } return true; }
深拷贝
function deepClone(data) { if (typeof data === 'object') { let result; if (data instanceof Array) { result = []; } else { result = {}; } for(let key in data) { // 保证key 不是原型的属性 if (data.hasOwnProperty(key)) { if (typeof data[key] !== 'object') { result[key] = data[key]; } else { result[key] = deepClone(data[key]); } } } return result; } else { return data; } }