0

I'm looking to optimise the following code block, interms of less code and speed. It simply merges 2 JavaScript objects into 1. Although it works fine, I'm sure this could be cleaner. Any help would be awesome.

Also it must be done in native JavaScript without using a library such as JQuery etc.

Cheers

function mergeObject(obj1, obj2) {
    var output = {};
    if (!obj2) {
        return obj1;
    }
    for (var prop in obj1) {
        if (prop in obj2) {
            output[prop] = obj2[prop];
        } else {
            output[prop] = obj1[prop];
        }
    }
    return output;
}
4

1 回答 1

0

您可以这样做,但请注意,a如果 in 中的属性也在b.

function(a, b) {
  if (a && b) {
    for (var key in b) {
      if (b.hasOwnProperty(key)) {
        a[key] = b[key];
      }
    }
  }
  return a;
}
于 2013-09-17T19:09:54.593 回答