在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();

你可能感兴趣的:(在javascript中如何置空数组(包含已被引用的数组))