如何在JavaScript中清空数组?

JavaScript

樱Mandy

2020-03-09

有没有一种方法可以清空数组.remove()

例如,

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

我该如何清空?

第202篇《如何在JavaScript中清空数组?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

14个回答
十三Tony伽罗 2020.03.09

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

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

我很惊讶还没有人建议这样做:

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

这将产生与其他解决方案完全不同的状态的数组。从某种意义上说,该数组已被“清空”:

xs
=> Array [ <4 empty slots> ]

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

xs.length
=> 4

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

您可以使用[,,,,]生成等效数组Array(4)

宝儿小哥小卤蛋 2020.03.09

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

const numbers = [1, 2, 3]

您不能重新分配:

numbers = []

您只能截断:

numbers.length = 0
逆天 2020.03.09

如果您正在使用

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.

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.

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.

小卤蛋小小 2020.03.09

使用Jan的初始建议的修改版本

var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
     A.pop();
}
神无神乐 2020.03.09
Array.prototype.clear = function() {
    this.length = 0;
};

并称之为: array.clear();

null 2020.03.09

A.splice(0);

我只是在我正在处理的某些代码上执行过此操作。它清除了数组。

猴子村村 2020.03.09

如果您对内存分配感兴趣,则可以使用类似jsfiddle的东西和chrome dev工具的“时间轴”标签来比较每种方法您将需要使用底部的垃圾桶图标“清除”阵列后强制进行垃圾收集。这应该为您选择的浏览器提供更明确的答案。这里有很多答案很老,我不会依赖它们,而是像上面@tanguy_k的答案一样进行测试。

(有关上述标签的介绍,您可以在此处查看

Stackoverflow迫使我复制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>

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

阿飞小卤蛋 2020.03.09

关于while的信息存在很多困惑和错误信息;在答案和评论中都出现流行/移位表现。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
    }
}

我创建了一个可以正常运行的新测试:

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

警告:即使在此版本的测试中,您实际上也看不到真正的区别,因为克隆阵列会占用大部分测试时间。它仍然显示这splice是清除阵列的最快方法(没有[]考虑,因为虽然这是最快的,但实际上并未清除现有阵列)。

理查德Stafan 2020.03.09

您可以将其添加到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),我倾向于同意。在决定如何处理时,请谨慎使用。

老丝老丝 2020.03.09

性能测试:

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
米亚Eva 2020.03.09

到目前为止,至少有2739票赞成的答案具有误导性和错误性。

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

  1. 说“ A = []是答案”是无知的,而且绝对不正确。[] == []错误的

    这是因为这两个数组是两个单独的,独立的对象,它们具有自己的两个标识,在数字世界中占据了自己的空间,每个空间都是自己的。


假设您的母亲要您清空垃圾桶。

  • 您不会带来新的功能,就好像您已经完成了要求的操作一样。
  • 相反,您清空垃圾箱。
  • 您不要用新的空罐替换装满的罐,也不要从装满的罐中取标签“ A”并将其粘贴到新的罐上。 A = [1,2,3,4]; A = [];

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!


  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.

神无阳光 2020.03.09

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

A.splice(0, A.length);

HarryL 2020.03.09

如果您需要保留原始数组,因为还有其他引用也需要更新,则可以通过将其长度设置为零来清除它而无需创建新数组:

A.length = 0;

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android