Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 110 期(数据结构-数组):清空数组 #113

Open
wingmeng opened this issue Sep 17, 2019 · 0 comments
Open

第 110 期(数据结构-数组):清空数组 #113

wingmeng opened this issue Sep 17, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

let arr = [1, 2, 3];

如何清空上面的数组?常见的方式有两种:

// 方法1:将数组长度改为 0
arr.length = 0;

// 方法2:重新赋值为空数组
arr = [];

这两种方法从运行结果上来看,似乎是一样的,但在一些细节上是有很大区别的:

  1. arr.length = 0 将数组长度改为 0 后,会清空数组,同时删除数组中的所有索引。

    let arr = [1, 2, 3];
    let arr1 = arr;
    
    arr.length = 0;
    console.log(arr1);  // 返回:[],因为它引用了 arr,此时 arr 中的索引被清空了,所以 arr1 也为空
  2. arr = [] 将数组赋值为空数组,只是改变了栈指针,之前被其他变量引用的数据仍有效。

    let arr = [1, 2, 3];
    let arr1 = arr;
    
    arr = [];
    console.log(arr1);  // 返回 [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant