有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
当前回答
Array.prototype.clear = function() {
this.length = 0;
};
并调用它:array.clear();
其他回答
如果您正在使用
a = [];
然后将新的数组引用分配给,如果中的引用已经分配给任何其他变量,那么它也不会清空该数组,因此垃圾收集器不会收集该内存。
例如。
var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];
or
a.length = 0;
当我们指定a.length时,我们只是重置数组和内存的边界,其余数组元素将由垃圾收集器连接。
而不是这两种解决方案更好。
a.splice(0,a.length)
and
while(a.length > 0) {
a.pop();
}
根据kenshou.html先前的回答,第二种方法更快。
您可以将其添加到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),我倾向于同意。在决定如何处理这件事时请谨慎。
性能测试:
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
Array.prototype.clear = function() {
this.length = 0;
};
并调用它:array.clear();
如果您对内存分配感兴趣,可以使用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管理字符串的方式不同于其他基本类型,更不用说对象数组了。类型可能会影响发生的情况。