需求是这样的,有两个对象为A和B,要将B的属性负值到A中.可以使用JavaScript中有Object.assign(target, sources)方法.

用法:

var c=Object.assign(a, b);

但是有个问题,该方法Object.assign()并不兼容IE浏览器,不得不说IE是真的垃圾.为了兼容IE,我们可以在使用前写个扩展:

if (typeof Object.assign != 'function') {
  Object.assign = function(target) {
    'use strict';
    if (target == null) {
      throw new TypeError('Cannot convert undefined or null to object');
    }
 
    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}

差不多就是这样了.

以上就是【js 根据对象a设置对象b属性】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论