Skip to content

[js] 第173天 清空一个数组的方式有哪些?它们有什么区别? #1313

Open
@haizhilin2013

Description

@haizhilin2013

第173天 清空一个数组的方式有哪些?它们有什么区别?

Activity

coconilu

coconilu commented on Oct 6, 2019

@coconilu

arr.length = 0;

Liuwan12

Liuwan12 commented on Oct 7, 2019

@Liuwan12

arr.splice(0,arr.length);

Via1877

Via1877 commented on Oct 8, 2019

@Via1877

arr = [];

nyz123

nyz123 commented on Oct 9, 2019

@nyz123

a = Array.of()

ZindexYG

ZindexYG commented on May 29, 2020

@ZindexYG

方法1

这是完美的,因为这实际上创建了一个全新的(空)数组
仅当您仅通过数组的原始变量A引用数组时才使用此选项。

let arr1 = [1,2,3]
let arr2 = arr1
arr1 = []
console.log(arr1,arr2) // [] [1,2,3]

方法2

通过将现有数组的长度设置为 0 来清除该数组
会影响元数组

const arr1 = [1,2,3]
const arr2 = arr1
arr1.length = 0
console.log(arr1,arr2) // [] []

方法3

.splice()函数将返回一个包含所有已删除项的数组,因此它实际上将返回原始数组的副本

const arr1 = [1,2,3]
const arr2 = arr1
arr1.splice(0,arr1.length)
console.log(arr1,arr2) // [] []

方法4

最慢的方法

const arr1 = [1,2,3]
const arr2 = arr1
while (arr1.length > 0) {
  arr1.pop()
}
console.log(arr1,arr2) // [] []
xiaoqiangz

xiaoqiangz commented on Aug 4, 2022

@xiaoqiangz

arr = [] ; arr.length = 0 ;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@coconilu@xiaoqiangz@nyz123@Via1877

        Issue actions

          [js] 第173天 清空一个数组的方式有哪些?它们有什么区别? · Issue #1313 · haizlin/fe-interview