我有两个对象字面值:
var animal = { eat: function() { console.log("eating..."); } } var dog = { eat: "this has to be replaced when merged",nrOfLegs: 4 }
需要这样的合并功能:
dog = someMergingFunction(animal,dog);
这产生:
{ eat: function() { console.log("eating..."); },nrOfLegs: 4 }
如何在Javascript中执行此操作?
解决方法
// usage merged = someMergingFunction(a,b,c,d,...) // keys in earlier args override keys in later args. // someMergingFunction({foo:"bar"},{foo:"baz"}) // ==> {foo:"bar"} function someMergingFunction () { var o = {} for (var i = arguments.length - 1; i >= 0; i --) { var s = arguments[i] for (var k in s) o[k] = s[k] } return o }