有没有方法清空数组,如果有可能,可以使用.remove()?

例如,

A = [1,2,3,4];

我怎么才能把它清空?


当前回答

如果您使用常量,则您别无选择:

const numbers = [1, 2, 3]

您不能重新设计:

numbers = []

您只能截断:

numbers.length = 0

其他回答

您可以将其添加到JavaScript文件中,以允许“清除”数组:

Array.prototype.clear = function() {
    this.splice(0, this.length);
};

然后可以这样使用:

var list = [1, 2, 3];
list.clear();

或者,如果你想确保你没有破坏一些东西:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
       this.splice(0, this.length);
    };
}

很多人认为不应该修改本机对象(如Array),我倾向于同意。在决定如何处理这件事时请谨慎。

您可以轻松地创建一个函数来实现这一点,更改长度,甚至将其作为remove()函数添加到本机Array中以供重用。

假设您有此阵列:

var arr = [1, 2, 3, 4, 5]; //the array

好的,只需运行以下命令:

arr.length = 0; //change the length

结果是:

[] //result

清空数组的简单方法。。。

也可以使用循环,这不是必须的,但只是另一种方法:

/* could be arr.pop() or arr.splice(0)
don't need to return as main array get changed */

function remove(arr) {
  while(arr.length) {
    arr.shift(); 
  }
}

你也可以考虑一些棘手的方法,例如:

arr.splice(0, arr.length); //[]

因此,如果arr有5项,它将从0拼接5项,这意味着数组中不会保留任何内容。

还有其他方法,例如简单地重新分配数组:

arr = []; //[]

如果您查看Array函数,有很多其他方法可以做到这一点,但最推荐的方法可能是更改长度。

正如我在开头所说的,你也可以原型remove(),因为它是你问题的答案。您可以简单地选择上面的方法之一,并将其原型化为JavaScript中的Array对象,例如:

Array.prototype.remove = Array.prototype.remove || function() {
  this.splice(0, this.length);
};

您可以像这样调用它来清空javascript应用程序中的任何数组:

arr.remove(); //[]

如果您使用常量,则您别无选择:

const numbers = [1, 2, 3]

您不能重新设计:

numbers = []

您只能截断:

numbers.length = 0

这里是保持相同数组(“可变”)的最快工作实现:

function clearArray(array) {
  while (array.length > 0) {
    array.pop();
  }
}

仅供参考,它不能简化为while(array.pop()):测试将失败。

仅供参考,Map和Set定义clear(),Array也可以使用clear(()。

TypeScript版本:

function clearArray<T>(array: T[]) {
  while (array.length > 0) {
    array.pop();
  }
}

相应的测试:

describe('clearArray()', () => {
  test('clear regular array', () => {
    const array = [1, 2, 3, 4, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });

  test('clear array that contains undefined and null', () => {
    const array = [1, undefined, 3, null, 5];
    clearArray(array);
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

这里是更新的jsPerf:http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

jsPerf脱机。类似基准:https://jsben.ch/hyj65

性能测试:

http://jsperf.com/array-clear-methods/3

a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length)  // 97% slower
while (a.length > 0) {
    a.pop();
} // Fastest