zoukankan      html  css  js  c++  java
  • 常用的浅拷贝实现方法

    常用的浅拷贝实现方法

    Object.assign

    ES6中拷贝对象的方法,接受的第一个参数是拷贝的目标target,剩下的参数是拷贝的源对象sources(可以是多个)

    let target = {};
    let source = {
    	a: '123',
    	b: {
    		name: 'javascript'
    	}
    }
    Object.assign(target,source);
    console.log(target); // {a:'123',b:{name:'javascript'}}
    

    Object.assign使用注意事项:

    • 只拷贝源对象的自身属性(不拷贝继承属性)
    • 不会拷贝对象不可枚举的属性
    • undefined和null无法转成对象,他们不能作为Object.assign参数,但是可以作为源对象
    • 属性名为Symbol 值的属性,可以被Object.assign拷贝

    Array.prototype.slice

    let array = [{a:1},{b:2}]
    let array1 = array.slice(0);
    console.log(array1)
    
    • slice:从已有的数组中返回选定的元素

    Array.prototype.concat

    let array = [{a:1},{b:2}]
    let array1 = [].concat(array)
    console.log(array1)
    

    扩展运算符

    let obj = {a:1,b:{c:1}}
    let obj2 = {...obj}
    console.log(obj2)
    
  • 相关阅读:
    codeforces 980A Links and Pearls
    zoj 3640 Help Me Escape
    sgu 495 Kids and Prizes
    poj 3071 Football
    hdu 3853 LOOPS
    hdu 4035 Maze
    hdu 4405 Aeroplane chess
    poj 2096 Collecting Bugs
    scu 4444 Travel
    zoj 3870 Team Formation
  • 原文地址:https://www.cnblogs.com/justyouadmin/p/13413990.html
Copyright © 2011-2022 走看看