在javascript中如何置空数组(包含已被引用的数组)

class EmptyArray {

  constructor() {}

  /*  1、arrayList = [];//该数组会被置空,引用的仍然存在  */

  emptyArrayOriginal() {

    let arrayList = ["a", "b", "c", "d", "e", "f", ""];

    let arrayList2 = arrayList;

    arrayList = [];

    console.log("emptyArrayOriginal")

    console.log(arrayList); //[]

    console.log(arrayList2); //  ["a", "b", "c", "d", "e", "f", ""]

  }

  /*    2、arrayList.length = 0 ;//包含引用该数组的也会被置空 */

  emptyArrayByLength() {

    let arrayList = ["a", "b", "c", "d", "e", "f", ""];

    let arrayList3 = arrayList;

    arrayList.length = 0;

    console.log("emptyArrayByLength")

    console.log(arrayList); //[]

    console.log(arrayList3); //[]

  }

  /*    3、arrayList.splice(0,arrayList.length);//包含引用该数组的也会被置空  */

  emptyArrayBySplice() {

    let arrayList = ["a", "b", "c", "d", "e", "f", ""];

    let arrayList4 = arrayList;

    arrayList.splice(0, arrayList.length);

    console.log("emptyArrayBySplice")

    console.log(arrayList); //[]

    console.log(arrayList4); //[]

  }

  /*  4、while(arrayList.length){ arrayList.pop() ;}//不推荐  */

  emptyArrayByWhile() {

    let arrayList = ["a", "b", "c", "d", "e", "f", ""];

    let arrayList5 = arrayList;

    while (arrayList.length) {

      arrayList.pop();

    }

    console.log("emptyArrayByWhile")

    console.log(arrayList); //[]

    console.log(arrayList5);//[]

  }

}

let ea = new EmptyArray();

ea.emptyArrayOriginal();

ea.emptyArrayByLength();

ea.emptyArrayBySplice();

ea.emptyArrayByWhile();

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容