JavaScript求数组Array的并集(javascript面试常见题目)
var Utils = { joinArray:function(source,target){ for(var i = 0;i<source.length;i++){ var oa = source[i]; for(var j = 0;j<target.length;j++){ var ob = target[j]; if(ob === undefined)continue; //break 语句用于跳出循环,continue 用于跳过循环中的一个迭代。 if(oa.id === ob.id){ Utils.copyProperties(oa,ob); target.splice(j,1); break; } } } for(var i = 0;i<target.length;i++){ source.push(target[i]); } return source; }, copyProperties:function(source,target){ for(var prop in target){ //遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。 source[prop] = target[prop]; } return source; } }; var a = [ {id: 10001, name: "Lisa", age: 16}, {id: 10002, name: "Bob", age: 22}, {id: 10003, name: "Alice", age: 20} ]; var b = [ {id: 10001, gender: "Female"}, {id: 10002, name: "Bob King", birthday: "1996-01-22"}, {id: 10005, name: "Tom", birthday: "2000-01-01"} ]; Utils.joinArray(a,b); console.log(a);