js对象的数组比较若不同,则返回对象的key
var oldObj = {key:old[]} , newObj = {key:new[]} ; //如果 newObj{new[]} 不等于 oldObj {old[]} 取出 key
/** * 对象比较 * @param o1 * @param o2 * @return */function equalObject(o1, o2){ if(typeof o1 != typeof o2)return false; if(o1 == null || o2 == null)return o1 == o2; if(typeof o1 == 'object'){ for (var o in o1){ if(typeof o2[o] == 'undefined')return false; if(!equalObject(o1[o],o2[o]))return false; } return true; }else{ return o1 == o2; } }
var oldObj = {name:[1,2],age:[4,5],...} , newObj = {name:[1,2],age:[4,5,6],...} ; // 这两个对象中 name 数组值相同,不用取了 ; // 其中 age 数组值不同, 取出 age来
要是有顺序的话,倒是可以用下面这种形式
var oldObj = {name:[1,2],age:[4,5]} , newObj = {name:[1,2],age:[4,5,6]} ;
for(var i in oldObj){
if(oldObj[i].join('')!=newObj[i].join('')){
alert(i)
}
}
var equal = function(o1, o2){ //null undefined NaN Number Date String Array Object RegExp 本函数只判断了这些类型 //Function Math Element 这些类型不做判断 var b; if(o1 == null && o1 === o2) return true; if(o1 == null || o2 == null) return false; if(o1.constructor != o2.constructor) return false; if(o1 instanceof Date || o1.constructor == Number) return o1 - o2 == 0; if(o1 instanceof Array){ b = o1.length == o2.length; if(b)for(var i = o1.length - 1; i >= 0; i--){ if(!b) return b; b = b && equal(o1[i], o2[i]) } return b } if(o1.constructor == String) return o1.localeCompare(o2) == 0; if(o1 instanceof RegExp) return o1.source == o2.source && o1.global == o2.global && o1.ignoreCase == o2.ignoreCase && o1.multiline == o2.multiline; var k1 = [], k2 = []; for(var p in o1) if(o1.hasOwnProperty(p)) k1.push(p); for(var p in o2) if(o2.hasOwnProperty(p)) k2.push(p); b = k1.length == k2.length; if(b)for(var i = k1.length - 1; i >= 0; i--){ if(!b) return b; b = b && equal(o1[k1[i]], o2[k2[i]]) } return b; }, distinct = function(o1, o2){ var b = [], t = {}; if(typeof o1 != 'object' || typeof o2 != 'object') return b; var k1 = [], k2 = []; for(var p in o1) if(!(o1[p] instanceof Function)) k1.push(p); for(var p in o2) if(!(o2[p] instanceof Function)) k2.push(p); for(var i = k1.length - 1; i >= 0; i--)if(!equal(o1[k1[i]], o2[k1[i]])) t[k1[i]] = 1; for(var i = k2.length - 1; i >= 0; i--)if(!equal(o1[k2[i]], o2[k2[i]])) t[k2[i]] = 1; for(var p in t)if(t.hasOwnProperty(p))b.push(p); t = null; return b; }; var o1 = {a:[1,2], c:1}, o2 = {a:[1,2,3], b:1}; alert('对象o1和o2不同的属性有:\r\n' + distinct(o1, o2))