ES6和promise和深拷贝浅拷贝

1  ES6 新增了双冒号运算符 , 用来取代以往的bind() , call() , 和apply()

foo :: bar  等同于  bar . bind(foo)

foo :: bar(...arguments) 等同于 bar .apply (foo , arguments)

2  在object原型上新增了getPrototypeOf() 和setPrototypeOf()方法 , 用来获取或设置当前对象的prototype对象 . 

3  object 原型上还新增了object.keys() , object.values() , object.entries() 方法 , 用来获取对象的所有键 , 所有值 , 和所有的键值对的数组 . 

4 输出的结果是

setTimeout(function () {
    console.log(1)

}, 0)
new Promise(function executor(resolve) {
    console.log(2)
    for (let i = 0; i < 10000; i++){
        i ==9999&&resolve()
    }
    console.log(3)
}).then(function () {
    console.log(4)
})
console.log(5)

//2 3 5 4 1

5 深拷贝和浅拷贝

// 浅拷贝:只拷贝最外面层
		
		let obj = {
			uname : '张三丰',
			age : 22,
			sex : '男',
			color : ['red', 'blue', 'yellow', 'pink'],
			message : {
				index : 1,
				score : 99,
			}
		}

		let newObj = {};

		// 方法
		Object.assign(newObj, obj);

		// obj.uname = 'aaa';
		// obj.message.index = 123;

		console.log( obj, newObj );


		// newObj.uname = obj.uname;
		// 遍历
		// for (let key in obj) {
		// 	// key:代表键
		// 	// console.log( obj[key] );
		// 	newObj[key] = obj[key];
		// }

		// // obj.uname = '阿飞飞';
		// obj.message.index = 666;

		// console.log( obj, newObj );

// 深拷贝:所有层都拷贝
		let obj = {
			uname : '张三丰',
			age : 22,
			sex : '男',
			color : ['red', 'blue', 'yellow', 'pink'],
			message : {
				index : 1,
				score : 99,
			}
		}

		let newObj = {};

		function kaobei (newObj, obj) {

			for (let key in obj) {
				if ( obj[key] instanceof Array ) { // obj[key]是数组
					// obj[key]满足条件就是数组
					newObj[key] = [];

					kaobei( newObj[key], obj[key] );
				} else if (obj[key] instanceof Object) { // obj[key]是对象
					newObj[key] = {};

					kaobei(newObj[key], obj[key])
				} else {
					newObj[key] = obj[key];
				}
			}

		}


		kaobei(newObj, obj)

		obj.message.index = 123;
		console.log( obj, newObj );
//深拷贝2
function clone(obj) {
    if (typeof obj == 'object') {
        if (obj instanceof Array) {
            let result = []
            for (let i = 0; i < obj.length; i++) {
                result[i] = clone(obj[i])
            }
            return result
        } else {
            let result = {}
            for (const key in obj) {
                    result[key] = clone(obj[key])
            }
            return result
        } 
    } else {
        return obj
    }
}
let obj1 = [12 , {a : 11 , b : 22} , 5]
let obj2 = clone(obj1)
obj2[1].a += 5
console.log('obj1的打印结果' , obj1 ,'obj2的打印结果' ,obj2)

//result  
//obj1的打印结果 [ 12, { a: 11, b: 22 }, 5 ] obj2的打印结果 [ 12, { a: 16, b: 22 }, 5 ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值