zoukankan      html  css  js  c++  java
  • 纯原生仿ES6的Object.assign,实现深度合并对象

    源码:

    function isObj(x){	
    	var type = typeof x;
    	return x !== null && (type === 'object' || type === 'function');
    }
    
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var propIsEnumerable = Object.prototype.propertyIsEnumerable;
    
    function toObject(val) {
    	if (val === null || val === undefined) {
    		throw new TypeError('Cannot convert undefined or null to object');
    	}
    
    	return Object(val);
    }
    
    function assignKey(to, from, key) {
    	var val = from[key];
    
    	if (val === undefined || val === null) {
    		return;
    	}
    
    	if (hasOwnProperty.call(to, key)) {
    		if (to[key] === undefined || to[key] === null) {
    			throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
    		}
    	}
    
    	if (!hasOwnProperty.call(to, key) || !isObj(val)) {
    		to[key] = val;
    	} else {
    		to[key] = assign(Object(to[key]), from[key]);
    	}
    }
    
    function assign(to, from) {
    	if (to === from) {
    		return to;
    	}
    
    	from = Object(from);
    
    	for (var key in from) {
    		if (hasOwnProperty.call(from, key)) {
    			assignKey(to, from, key);
    		}
    	}
    
    	if (Object.getOwnPropertySymbols) {
    		var symbols = Object.getOwnPropertySymbols(from);
    
    		for (var i = 0; i < symbols.length; i++) {
    			if (propIsEnumerable.call(from, symbols[i])) {
    				assignKey(to, from, symbols[i]);
    			}
    		}
    	}
    
    	return to;
    }
    
    function deepAssign(target) {
    	target = toObject(target);
    
    	for (var s = 1; s < arguments.length; s++) {
    		assign(target, arguments[s]);
    	}
    
    	return target;
    };
    

      

    调用:

    deepAssign({a: {b: 0}}, {a: {b: 1, c: 2}}, {a: {c: 3}});
    //=> {a: {b: 1, c: 3}}
    

      

  • 相关阅读:
    Qt读取JSON和XML数据
    IOS设计模式学习(19)策略
    Android学习笔记(二)之异步加载图片
    ETL-Career RoadMap
    HDU 1501 & POJ 2192 Zipper(dp记忆化搜索)
    CodeForces 242E
    推荐:室内定位API
    基于单片机的电子密码锁的实现
    [nagios监控] NRPE: Unable to read output 的原因及排除
    (ubuntu)在andorid andk工程中使用ccache加速编译速度
  • 原文地址:https://www.cnblogs.com/wln3344/p/5601556.html
Copyright © 2011-2022 走看看