有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
有没有方法清空数组,如果有可能,可以使用.remove()?
例如,
A = [1,2,3,4];
我怎么才能把它清空?
当前回答
如果您使用常量,则您别无选择:
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
如果您正在使用
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先前的回答,第二种方法更快。
关于这段时间,有很多困惑和错误信息;回答和评论中的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
您可以将其添加到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),我倾向于同意。在决定如何处理这件事时请谨慎。