美文网首页
clone数组的5种方式

clone数组的5种方式

作者: 星星赐福 | 来源:发表于2020-10-27 17:55 被阅读0次

    数组对象在JavaScript中默认是引用类型。顾名思义、它是引用实际值,而自身不是实际值。由于这个原因,使用赋值操作(=)拷贝数组只是拷贝原始值的引用而不是实际的值。
    在本文中,我们将介绍用JavaScript实际复制数组的5种方法。

    1、扩展运算符

    let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
    console.log(clubs)
    
    //Create a clone Es6 way
    let clonedClubs = [...clubs]
    console.log(clonedClubs)
    

    2、for() 循环

    let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
    clonedClubs = [];
    for (i = 0; i < clubs.length; i++) {
      clonedClubs[i] = clubs[i];
    }
    console.log(clonedClubs)
    

    3、Array map()

    let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
    cloning = (i) => i;
    
    clonedClubs = clubs.map(cloning)
    console.log(clonedClubs)
    

    4、Array filter()

    let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
    
    clonedClubs = clubs.slice();
    console.log(clonedClubs)
    

    4、Array slice()

    let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
    
    clonedClubs = clubs.slice();
    console.log(clonedClubs)
    

    相关文章

      网友评论

          本文标题:clone数组的5种方式

          本文链接:https://www.haomeiwen.com/subject/bvixvktx.html