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

例如,

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

我怎么才能把它清空?


当前回答

您可以轻松地创建一个函数来实现这一点,更改长度,甚至将其作为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(); //[]

其他回答

关于这段时间,有很多困惑和错误信息;回答和评论中的pop/shift表现。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

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

性能测试:

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

如果您对内存分配感兴趣,可以使用jsfiddle这样的东西与chrome开发工具的时间线选项卡来比较每种方法。您将希望在“清除”阵列后使用底部的垃圾箱图标强制垃圾收集。这将为您选择的浏览器提供更明确的答案。这里的很多答案都是旧的,我不会依赖它们,而是像上面@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管理字符串的方式不同于其他基本类型,更不用说对象数组了。类型可能会影响发生的情况。

使用拼接方法清空数组A的内容是一种更易于跨浏览器且更优化的解决方案,如下所示:

A.拼接(0,A.长度);

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

A.length = 0;