如何在JavaScript中清空数组?

时间:2022-08-11 07:21:09

Is there a way to empty an array and if so possibly with .remove()?

是否有一种清空数组的方法,如果可能的话,可以使用.remove()?

For instance,

例如,

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

How can I empty that?

我怎么能把它清空呢?

18 个解决方案

#1


3346  

Ways to clear an existing array A:

清除现有阵列A的方法:

Method 1

方法1

(this was my original answer to the question)

(这是我最初的回答)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

这段代码将变量A设置为一个新的空数组。如果您没有对原始数组A的引用,这是完美的,因为这实际上创建了一个全新的(空的)数组。您应该小心使用这个方法,因为如果您从另一个变量或属性引用了这个数组,那么原始数组将保持不变。仅当您仅引用数组的原始变量A时才使用此方法。

This is also the fastest solution.

这也是最快的解决方案。

This code sample shows the issue you can encounter when using this method:

此代码示例显示了使用此方法时可能遇到的问题:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

方法二(如Matthew Crumley建议)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

这将通过将数组的长度设置为0来清除现有的数组。有些人认为这可能在JavaScript的所有实现中都不起作用,但事实证明并非如此。当在ECMAScript 5中使用“严格模式”时,它也是有效的,因为数组的长度属性是读/写属性。

Method 3 (as suggested by Anthony)

方法3 (Anthony建议)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

使用.splice()可以很好地工作,但是由于.splice()函数将返回一个包含所有删除项的数组,因此它实际上会返回原始数组的副本。基准表明,这对性能没有任何影响。

Method 4 (as suggested by tanguy_k)

方法4 (tanguy_k建议)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

这个解决方案不是很简洁,而且也是最慢的解决方案,与原始答案中引用的早期基准相反。

Performance

性能

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

在所有清除现有数组的方法中,方法2和方法3在性能上非常相似,并且比方法4快得多。看到这个基准。

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

正如Diadistis在下面的回答中指出的,最初用来确定上述四种方法性能的基准是有缺陷的。最初的基准测试重用已清除的数组,因此第二次迭代正在清除一个已经为空的数组。

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).

下面的基准修复了这个缺陷:http://jsben.ch/#/hyj65。它清楚地显示了方法#2 (length属性)和#3 (splice)是最快的(不包括方法#1,它不会改变原始数组)。


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.

这一直是一个热门话题,也引起了很多争议。实际上有很多正确的答案,因为这个答案已经被标记为被接受的答案很长时间了,我将在这里包含所有的方法。如果你对这个答案投赞成票,请把我提到的其他答案也投赞成票。

#2


2233  

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

如果你需要保留原来的数组,因为你还有其他的引用需要更新,你可以不创建一个新的数组,将它的长度设为0:

A.length = 0;

#3


253  

Here the fastest working implementation while keeping the same array ("mutable"):

这里是运行速度最快的实现,同时保持相同的数组(“mutablecopy”):

Array.prototype.clear = function() {
  while (this.length) {
    this.pop();
  }
};

FYI Map defines clear() so it would seem logical to have clear() for Array too.

FYI Map定义了clear(),所以数组也应该有clear()。

Or as an Underscore.js mixin:

或作为一个下划线。js混合:

_.mixin({
  clearArray: function(array) {
    while (array.length) {
      array.pop();
    }
  }
});

Or a simple function:

或一个简单的函数:

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

TypeScript version:

打字文件版本:

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

FYI it cannot be simplified to while (array.pop()): the tests will fail.

提示:不能将其简化为while (array.pop()):测试将失败。

And the tests that goes with it:

与之相关的测试:

describe('Array', () => {
  it('should clear the array', () => {
    let array = [1, 2, 3, 4, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);

    // Even with undefined or null inside
    array = [1, undefined, 3, null, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

这里更新的jsPerf: http://jsperf.com/array-驱逐舰/32 http://jsperf.com/array-驱逐舰/152

#4


178  

A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:

使用splice方法将数组A的内容清空如下所示,将是一种更友好、更优化的跨浏览器解决方案:

A.splice(0, A.length);

一个。拼接(0,A.length);

#5


58  

Performance test:

性能测试:

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

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

#6


56  

The answers that have no less that 2739 upvotes by now are misleading and incorrect.

到目前为止,高达2739票的答案是错误的。

The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].

问题是:“如何清空现有数组?”例如A =[1,2,3,4]。

  1. Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.

    说“A =[]就是答案”是无知和绝对错误的。[] =[]是假的。

    This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.

    这是因为这两个数组是两个独立的、独立的对象,具有各自的两个身份,各自在数字世界中占据着自己的空间,各自独立。


Let's say your mother asks you to empty the trash can.

比方说,你妈妈让你清空垃圾桶。

  • You don't bring in a new one as if you've done what you've been asked for.
  • 你不会带一个新的来,就好像你已经完成了要求你做的一样。
  • Instead, you empty the trash can.
  • 相反,你倒空垃圾桶。
  • You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];
  • 你不需要用一个新的空罐子来替换填充的罐子,也不需要从填充的罐子中取出标签“a”并将它粘在新的罐子上,就像a = [1,2,3,4];一个=[];

Emptying an array object is the easiest thing ever:

清空数组对象是最简单的事情:

A.length = 0;

This way, the can under "A" is not only empty, but also as clean as new!

这样,在“A”下的can不仅是空的,而且是干净的!


  1. Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:

    此外,你不需要手工清除垃圾,直到罐头是空的!你被要求一次彻底清空现有的垃圾桶,直到垃圾桶变空,比如:

    while(A.length > 0) {
        A.pop();
    }
    
  2. Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:

    也不要把你的左手放在垃圾桶的底部,用你的右手拿着它,这样就能把它的内容拉出来:

    A.splice(0, A.length);
    

No, you were asked to empty it:

不,你被要求清空它:

A.length = 0;

This is the only code that correctly empties the contents of a given JavaScript array.

这是唯一正确清空给定JavaScript数组内容的代码。

#7


32  

You can add this to your JavaScript file to allow your arrays to be "cleared":

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

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

Then you can use it like this:

然后你可以这样使用它:

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

Or if you want to be sure you don't destroy something:

或者如果你想确定你没有破坏什么东西:

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

Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.

许多人认为不应该修改本机对象(如数组),我倾向于同意。请慎重决定如何处理此事。

#8


17  

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

And call it: array.clear();

叫它:array.clear();

#9


15  

There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:

关于这段时间,有很多困惑和错误的信息;在回答和评论中都有流行/换班的表现。while/pop解决方案的性能(如预期的那样)最差。实际发生的情况是,安装程序只对循环中运行代码片段的每个示例运行一次。例如:

var arr = [];

for (var i = 0; i < 100; i++) { 
    arr.push(Math.random()); 
}

for (var j = 0; j < 1000; j++) {
    while (arr.length > 0) {
        arr.pop(); // this executes 100 times, not 100000
    }
}

I have created a new test that works correctly :

我创建了一个新的测试,它运行正确:

http://jsperf.com/empty-javascript-array-redux

http://jsperf.com/empty-javascript-array-redux

Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).

警告:即使在这个版本的测试中,您也不能看到真正的差异,因为克隆数组占用了大部分测试时间。它仍然表明splice是清除数组的最快方式(没有考虑[],因为它是最快的,但是它实际上并没有清除现有的数组)。

#10


14  

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

如果您对内存分配感兴趣,可以使用类似于jsfiddle的chrome开发工具的时间轴标签来比较每种方法。您将希望使用底部的垃圾箱图标在“清除”数组之后强制进行垃圾收集。这将为您选择的浏览器提供更明确的答案。这里有很多答案都是旧的,我不会依赖它们,而是像上面@tanguy_k的答案一样进行测试。

(for an intro to the aforementioned tab you can check out here)

(对于前面提到的选项卡,你可以在这里查看)

* forces me to copy the jsfiddle so here it is:

*迫使我复制了jsfiddle

<html>
<script>
var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size
}

function scaffold()
{
  console.log("processing Scaffold...");
  a = new Array
}
function start()
{
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){
    a[i]="something"
  }
  console.log("done...")
}

function tearDown()
{
  console.log("processing teardown");
  a.length=0
}

</script>
<body>
    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>
    <br/>
</body>
</html>

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

您应该注意,它可能取决于数组元素的类型,因为javascript管理字符串的方式与其他基本类型不同,更不用说对象数组了。类型可能会影响发生的事情。

#11


10  

A.splice(0);

A.splice(0);

I just did this on some code I am working on. It cleared the array.

我只是对我正在处理的一些代码做了这个。这扫清了数组。

#12


9  

If you are using

如果您使用的是

a = []; 

Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.

然后,您将为a分配新的数组引用,如果在a中的引用已经被分配给任何其他变量,那么它也不会清空该数组,因此垃圾收集器将不会收集该内存。

For ex.

前女友。

var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];

or

a.length = 0;

When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.

当我们指定一个。长度,我们只是重新设置数组的边界,rest数组元素的内存将由垃圾收集器连接。

Instead of these two solutions are better.

而不是这两个解决方案更好。

a.splice(0,a.length)

and

while(a.length > 0) {
    a.pop();
}

As per previous answer by kenshou.html, second method is faster.

根据kenshou之前的回答。html,第二种方法更快。

#13


8  

Use a modified version of Jan's initial suggestion:

使用简最初建议的修改版本:

var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
     A.pop();
}

#14


5  

If you use constants then you have no choice:

如果你使用常数,那么你没有选择:

const numbers = [1, 2, 3]

You can not reasign:

你不能转让:

numbers = []

You can only truncate:

你只能截断:

numbers.length = 0

#15


3  

You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse.

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

Imagine you have this array:

假设你有这个数组:

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

OK, just simply run this:

好的,简单运行一下:

arr.length = 0; //change the length

and the result is:

结果是:

[] //result

easy way to empty an array...

清空数组的简单方法……

Also using loop which is not necessary but just another way to do that:

也使用循环,这不是必要的,但只是另一种方法

/* 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(); 
  }
}

There are also tricky way which you can think about, for example something like this:

你也可以考虑一些棘手的问题,例如:

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

So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array.

如果arr有5个元素,它会将5个元素从0拼接起来,这意味着数组中不会剩下任何东西。

Also other ways like simply reassign the array for example:

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

arr = []; //[]

If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length.

如果你看一下数组函数,还有很多其他的方法,但是最推荐的方法可能是改变长度。

As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like:

正如我在第一个地方所说的,您也可以原型移除(),因为它是您问题的答案。您可以简单地选择上面的方法之一,并将其原型化为JavaScript中的数组对象,如下所示:

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

and you can simply call it like this to empty any array in your javascript application:

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

arr.remove(); //[]

#16


2  

I'm surprised no one has suggested this yet:

我很惊讶没有人提出这个问题:

let xs = [1,2,3,4];
for (let i in xs)
    delete xs[i];

This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied':

这就产生了一个与其他解决方案相当不同的状态的数组。从某种意义上说,数组已经被“清空”:

xs
=> Array [ <4 empty slots> ]

[...xs]
=> Array [ undefined, undefined, undefined, undefined ]

xs.length
=> 4

xs[0]
=> ReferenceError: reference to undefined property xs[0]

You can produce an equivalent array with [,,,,] or Array(4)

您可以使用[、、、、]或数组(4)生成等效的数组

#17


2  

如何在JavaScript中清空数组?

To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'

要清空数组的当前内存位置,请使用:'myArray '。长度= 0'或'myArray.pop() -直到其长度为0'

  • length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
  • 长度:可以将length属性设置为随时截断一个数组。当您通过更改其长度属性来扩展数组时,实际元素的数量会增加。
  • pop() : The pop method removes the last element from an array and returns that returns the removed value.
  • pop(): pop方法从数组中移除最后一个元素,并返回返回值。
  • shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
  • shift(): shift方法删除zeroeth索引上的元素,将连续索引上的值向下移动,然后返回被删除的值。

Example:

例子:

var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]

var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];

var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);

refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);

mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);

mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);

Array.prototype.poptill_length = function (e) {
  while (this.length) {
    if( this.length == e ) break;

    console.log('removed last element:', this.pop());
  }
};

  • new Array() | [] Create an Array with new memory location by using Array constructor or array literal.

    新的Array() |[]使用数组构造函数或数组文字创建具有新内存位置的数组。

    mainArr = []; // a new empty array is addressed to mainArr.
    
    var arr = new Array('10'); // Array constructor
    arr.unshift('1'); // add to the front
    arr.push('15'); // add to the end
    console.log("After Adding : ", arr); // ["1", "10", "15"]
    
    arr.pop(); // remove from the end
    arr.shift(); // remove from the front
    console.log("After Removing : ", arr); // ["10"]
    
    var arrLit = ['14', '17'];
    console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
    
    function indexedItem( arr ) {
        var indexedStr = "";
        arr.forEach(function(item, index, array) {
            indexedStr += "{"+index+","+item+"}";
            console.log(item, index);
        });
        return indexedStr;
    }
    
  • slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.

    slice():通过使用slice函数,我们从原始数组中获得了一个较浅的元素副本,并带有新的内存地址,因此对cloneArr的任何修改都不会影响到实际的|原始数组。

    var shallowCopy = mainArr.slice(); // this is how to make a copy
    
    var cloneArr = mainArr.slice(0, 3); 
    console.log('Main', mainArr, '\tCloned', cloneArr);
    
    cloneArr.length = 0; // Clears current memory location of an array.
    console.log('Main', mainArr, '\tCloned', cloneArr);
    

#18


-2  

Use below if you need to empty Angular 2+ FormArray.

如果你需要空角2+ FormArray,请在下面使用。

public emptyFormArray(formArray:FormArray) {
    for (let i = formArray.controls.length - 1; i >= 0; i--) {
        formArray.removeAt(i);
    }
}

#1


3346  

Ways to clear an existing array A:

清除现有阵列A的方法:

Method 1

方法1

(this was my original answer to the question)

(这是我最初的回答)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

这段代码将变量A设置为一个新的空数组。如果您没有对原始数组A的引用,这是完美的,因为这实际上创建了一个全新的(空的)数组。您应该小心使用这个方法,因为如果您从另一个变量或属性引用了这个数组,那么原始数组将保持不变。仅当您仅引用数组的原始变量A时才使用此方法。

This is also the fastest solution.

这也是最快的解决方案。

This code sample shows the issue you can encounter when using this method:

此代码示例显示了使用此方法时可能遇到的问题:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

方法二(如Matthew Crumley建议)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

这将通过将数组的长度设置为0来清除现有的数组。有些人认为这可能在JavaScript的所有实现中都不起作用,但事实证明并非如此。当在ECMAScript 5中使用“严格模式”时,它也是有效的,因为数组的长度属性是读/写属性。

Method 3 (as suggested by Anthony)

方法3 (Anthony建议)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

使用.splice()可以很好地工作,但是由于.splice()函数将返回一个包含所有删除项的数组,因此它实际上会返回原始数组的副本。基准表明,这对性能没有任何影响。

Method 4 (as suggested by tanguy_k)

方法4 (tanguy_k建议)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

这个解决方案不是很简洁,而且也是最慢的解决方案,与原始答案中引用的早期基准相反。

Performance

性能

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

在所有清除现有数组的方法中,方法2和方法3在性能上非常相似,并且比方法4快得多。看到这个基准。

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

正如Diadistis在下面的回答中指出的,最初用来确定上述四种方法性能的基准是有缺陷的。最初的基准测试重用已清除的数组,因此第二次迭代正在清除一个已经为空的数组。

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).

下面的基准修复了这个缺陷:http://jsben.ch/#/hyj65。它清楚地显示了方法#2 (length属性)和#3 (splice)是最快的(不包括方法#1,它不会改变原始数组)。


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.

这一直是一个热门话题,也引起了很多争议。实际上有很多正确的答案,因为这个答案已经被标记为被接受的答案很长时间了,我将在这里包含所有的方法。如果你对这个答案投赞成票,请把我提到的其他答案也投赞成票。

#2


2233  

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

如果你需要保留原来的数组,因为你还有其他的引用需要更新,你可以不创建一个新的数组,将它的长度设为0:

A.length = 0;

#3


253  

Here the fastest working implementation while keeping the same array ("mutable"):

这里是运行速度最快的实现,同时保持相同的数组(“mutablecopy”):

Array.prototype.clear = function() {
  while (this.length) {
    this.pop();
  }
};

FYI Map defines clear() so it would seem logical to have clear() for Array too.

FYI Map定义了clear(),所以数组也应该有clear()。

Or as an Underscore.js mixin:

或作为一个下划线。js混合:

_.mixin({
  clearArray: function(array) {
    while (array.length) {
      array.pop();
    }
  }
});

Or a simple function:

或一个简单的函数:

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

TypeScript version:

打字文件版本:

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

FYI it cannot be simplified to while (array.pop()): the tests will fail.

提示:不能将其简化为while (array.pop()):测试将失败。

And the tests that goes with it:

与之相关的测试:

describe('Array', () => {
  it('should clear the array', () => {
    let array = [1, 2, 3, 4, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);

    // Even with undefined or null inside
    array = [1, undefined, 3, null, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

这里更新的jsPerf: http://jsperf.com/array-驱逐舰/32 http://jsperf.com/array-驱逐舰/152

#4


178  

A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:

使用splice方法将数组A的内容清空如下所示,将是一种更友好、更优化的跨浏览器解决方案:

A.splice(0, A.length);

一个。拼接(0,A.length);

#5


58  

Performance test:

性能测试:

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

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

#6


56  

The answers that have no less that 2739 upvotes by now are misleading and incorrect.

到目前为止,高达2739票的答案是错误的。

The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].

问题是:“如何清空现有数组?”例如A =[1,2,3,4]。

  1. Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.

    说“A =[]就是答案”是无知和绝对错误的。[] =[]是假的。

    This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.

    这是因为这两个数组是两个独立的、独立的对象,具有各自的两个身份,各自在数字世界中占据着自己的空间,各自独立。


Let's say your mother asks you to empty the trash can.

比方说,你妈妈让你清空垃圾桶。

  • You don't bring in a new one as if you've done what you've been asked for.
  • 你不会带一个新的来,就好像你已经完成了要求你做的一样。
  • Instead, you empty the trash can.
  • 相反,你倒空垃圾桶。
  • You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];
  • 你不需要用一个新的空罐子来替换填充的罐子,也不需要从填充的罐子中取出标签“a”并将它粘在新的罐子上,就像a = [1,2,3,4];一个=[];

Emptying an array object is the easiest thing ever:

清空数组对象是最简单的事情:

A.length = 0;

This way, the can under "A" is not only empty, but also as clean as new!

这样,在“A”下的can不仅是空的,而且是干净的!


  1. Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:

    此外,你不需要手工清除垃圾,直到罐头是空的!你被要求一次彻底清空现有的垃圾桶,直到垃圾桶变空,比如:

    while(A.length > 0) {
        A.pop();
    }
    
  2. Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:

    也不要把你的左手放在垃圾桶的底部,用你的右手拿着它,这样就能把它的内容拉出来:

    A.splice(0, A.length);
    

No, you were asked to empty it:

不,你被要求清空它:

A.length = 0;

This is the only code that correctly empties the contents of a given JavaScript array.

这是唯一正确清空给定JavaScript数组内容的代码。

#7


32  

You can add this to your JavaScript file to allow your arrays to be "cleared":

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

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

Then you can use it like this:

然后你可以这样使用它:

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

Or if you want to be sure you don't destroy something:

或者如果你想确定你没有破坏什么东西:

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

Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.

许多人认为不应该修改本机对象(如数组),我倾向于同意。请慎重决定如何处理此事。

#8


17  

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

And call it: array.clear();

叫它:array.clear();

#9


15  

There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:

关于这段时间,有很多困惑和错误的信息;在回答和评论中都有流行/换班的表现。while/pop解决方案的性能(如预期的那样)最差。实际发生的情况是,安装程序只对循环中运行代码片段的每个示例运行一次。例如:

var arr = [];

for (var i = 0; i < 100; i++) { 
    arr.push(Math.random()); 
}

for (var j = 0; j < 1000; j++) {
    while (arr.length > 0) {
        arr.pop(); // this executes 100 times, not 100000
    }
}

I have created a new test that works correctly :

我创建了一个新的测试,它运行正确:

http://jsperf.com/empty-javascript-array-redux

http://jsperf.com/empty-javascript-array-redux

Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).

警告:即使在这个版本的测试中,您也不能看到真正的差异,因为克隆数组占用了大部分测试时间。它仍然表明splice是清除数组的最快方式(没有考虑[],因为它是最快的,但是它实际上并没有清除现有的数组)。

#10


14  

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

如果您对内存分配感兴趣,可以使用类似于jsfiddle的chrome开发工具的时间轴标签来比较每种方法。您将希望使用底部的垃圾箱图标在“清除”数组之后强制进行垃圾收集。这将为您选择的浏览器提供更明确的答案。这里有很多答案都是旧的,我不会依赖它们,而是像上面@tanguy_k的答案一样进行测试。

(for an intro to the aforementioned tab you can check out here)

(对于前面提到的选项卡,你可以在这里查看)

* forces me to copy the jsfiddle so here it is:

*迫使我复制了jsfiddle

<html>
<script>
var size = 1000*100
window.onload = function() {
  document.getElementById("quantifier").value = size
}

function scaffold()
{
  console.log("processing Scaffold...");
  a = new Array
}
function start()
{
  size = document.getElementById("quantifier").value
  console.log("Starting... quantifier is " + size);
  console.log("starting test")
  for (i=0; i<size; i++){
    a[i]="something"
  }
  console.log("done...")
}

function tearDown()
{
  console.log("processing teardown");
  a.length=0
}

</script>
<body>
    <span style="color:green;">Quantifier:</span>
    <input id="quantifier" style="color:green;" type="text"></input>
    <button onclick="scaffold()">Scaffold</button>
    <button onclick="start()">Start</button>
    <button onclick="tearDown()">Clean</button>
    <br/>
</body>
</html>

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

您应该注意,它可能取决于数组元素的类型,因为javascript管理字符串的方式与其他基本类型不同,更不用说对象数组了。类型可能会影响发生的事情。

#11


10  

A.splice(0);

A.splice(0);

I just did this on some code I am working on. It cleared the array.

我只是对我正在处理的一些代码做了这个。这扫清了数组。

#12


9  

If you are using

如果您使用的是

a = []; 

Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.

然后,您将为a分配新的数组引用,如果在a中的引用已经被分配给任何其他变量,那么它也不会清空该数组,因此垃圾收集器将不会收集该内存。

For ex.

前女友。

var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];

or

a.length = 0;

When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.

当我们指定一个。长度,我们只是重新设置数组的边界,rest数组元素的内存将由垃圾收集器连接。

Instead of these two solutions are better.

而不是这两个解决方案更好。

a.splice(0,a.length)

and

while(a.length > 0) {
    a.pop();
}

As per previous answer by kenshou.html, second method is faster.

根据kenshou之前的回答。html,第二种方法更快。

#13


8  

Use a modified version of Jan's initial suggestion:

使用简最初建议的修改版本:

var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
     A.pop();
}

#14


5  

If you use constants then you have no choice:

如果你使用常数,那么你没有选择:

const numbers = [1, 2, 3]

You can not reasign:

你不能转让:

numbers = []

You can only truncate:

你只能截断:

numbers.length = 0

#15


3  

You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse.

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

Imagine you have this array:

假设你有这个数组:

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

OK, just simply run this:

好的,简单运行一下:

arr.length = 0; //change the length

and the result is:

结果是:

[] //result

easy way to empty an array...

清空数组的简单方法……

Also using loop which is not necessary but just another way to do that:

也使用循环,这不是必要的,但只是另一种方法

/* 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(); 
  }
}

There are also tricky way which you can think about, for example something like this:

你也可以考虑一些棘手的问题,例如:

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

So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array.

如果arr有5个元素,它会将5个元素从0拼接起来,这意味着数组中不会剩下任何东西。

Also other ways like simply reassign the array for example:

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

arr = []; //[]

If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length.

如果你看一下数组函数,还有很多其他的方法,但是最推荐的方法可能是改变长度。

As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like:

正如我在第一个地方所说的,您也可以原型移除(),因为它是您问题的答案。您可以简单地选择上面的方法之一,并将其原型化为JavaScript中的数组对象,如下所示:

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

and you can simply call it like this to empty any array in your javascript application:

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

arr.remove(); //[]

#16


2  

I'm surprised no one has suggested this yet:

我很惊讶没有人提出这个问题:

let xs = [1,2,3,4];
for (let i in xs)
    delete xs[i];

This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied':

这就产生了一个与其他解决方案相当不同的状态的数组。从某种意义上说,数组已经被“清空”:

xs
=> Array [ <4 empty slots> ]

[...xs]
=> Array [ undefined, undefined, undefined, undefined ]

xs.length
=> 4

xs[0]
=> ReferenceError: reference to undefined property xs[0]

You can produce an equivalent array with [,,,,] or Array(4)

您可以使用[、、、、]或数组(4)生成等效的数组

#17


2  

如何在JavaScript中清空数组?

To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'

要清空数组的当前内存位置,请使用:'myArray '。长度= 0'或'myArray.pop() -直到其长度为0'

  • length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
  • 长度:可以将length属性设置为随时截断一个数组。当您通过更改其长度属性来扩展数组时,实际元素的数量会增加。
  • pop() : The pop method removes the last element from an array and returns that returns the removed value.
  • pop(): pop方法从数组中移除最后一个元素,并返回返回值。
  • shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
  • shift(): shift方法删除zeroeth索引上的元素,将连续索引上的值向下移动,然后返回被删除的值。

Example:

例子:

var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]

var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];

var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);

refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);

mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);

mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);

Array.prototype.poptill_length = function (e) {
  while (this.length) {
    if( this.length == e ) break;

    console.log('removed last element:', this.pop());
  }
};

  • new Array() | [] Create an Array with new memory location by using Array constructor or array literal.

    新的Array() |[]使用数组构造函数或数组文字创建具有新内存位置的数组。

    mainArr = []; // a new empty array is addressed to mainArr.
    
    var arr = new Array('10'); // Array constructor
    arr.unshift('1'); // add to the front
    arr.push('15'); // add to the end
    console.log("After Adding : ", arr); // ["1", "10", "15"]
    
    arr.pop(); // remove from the end
    arr.shift(); // remove from the front
    console.log("After Removing : ", arr); // ["10"]
    
    var arrLit = ['14', '17'];
    console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
    
    function indexedItem( arr ) {
        var indexedStr = "";
        arr.forEach(function(item, index, array) {
            indexedStr += "{"+index+","+item+"}";
            console.log(item, index);
        });
        return indexedStr;
    }
    
  • slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.

    slice():通过使用slice函数,我们从原始数组中获得了一个较浅的元素副本,并带有新的内存地址,因此对cloneArr的任何修改都不会影响到实际的|原始数组。

    var shallowCopy = mainArr.slice(); // this is how to make a copy
    
    var cloneArr = mainArr.slice(0, 3); 
    console.log('Main', mainArr, '\tCloned', cloneArr);
    
    cloneArr.length = 0; // Clears current memory location of an array.
    console.log('Main', mainArr, '\tCloned', cloneArr);
    

#18


-2  

Use below if you need to empty Angular 2+ FormArray.

如果你需要空角2+ FormArray,请在下面使用。

public emptyFormArray(formArray:FormArray) {
    for (let i = formArray.controls.length - 1; i >= 0; i--) {
        formArray.removeAt(i);
    }
}