如何清空 JavaScript 中的数组?

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

For instance,

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

How can I empty that?

转载于:https://stackoverflow.com/questions/1232040/how-do-i-empty-an-array-in-javascript

csdnceshi76
斗士狗 here a benchmark with different possibilities: jsben.ch/#/7QyI1
大约 4 年之前 回复

17个回答

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.

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.

csdnceshi66
必承其重 | 欲带皇冠 var a = [1]; var b = a; a.length = 0; console.log(b) prints Array [ ], so it doesn't seem like it's creating a new array to me.
大约 3 年之前 回复
csdnceshi65
larry*wei I tried it on most of browsers, like IE, Firefox, Chrome, it is creating new array. If you set length greater than 0 then it will create an array with undefined elements, i.e. it will just hold some memory locations.
接近 6 年之前 回复
weixin_41568184
叼花硬汉 Do you have any source to confirm which JS engines will create a new array when a.length=0; is performed? How would those engines act for a.length=500; and a.length=4;?
接近 6 年之前 回复
csdnceshi65
larry*wei I just want to focus about actual memory representation about array
接近 6 年之前 回复
csdnceshi50
三生石@ Apart from being wrong on a.length, I don't see what this new answer adds to the thread?
接近 6 年之前 回复

Performance test:

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
csdnceshi77
狐狸.fox the performance results have changed quite a lot over the years - amazing how different the different versions of Chrome seem to be... redefine is the clear performance winner for Chrome 68. (but still does not solve the problem)
大约 2 年之前 回复
weixin_41568127
?yb? show some benchmarks to support your answer
3 年多之前 回复
csdnceshi79
python小菜 Please delete this answer as it is wrong, and links to a meaningless flawed test as fake evidence.
3 年多之前 回复
weixin_41568183
零零乙 It's not. It's the slowest method. The benchmark test is flawed.
接近 4 年之前 回复
csdnceshi53
Lotus@ There is definitely something fishy in this test result under Chrome. How in hell can the popping loop be that much faster then the other 3 solutions?
4 年多之前 回复
csdnceshi76
斗士狗 of course that creating a new instance of the array is faster than looping and popping it... so if popping is faster in chrome means the creation of a new array creation is buggy
5 年多之前 回复
csdnceshi72
谁还没个明天 Testing in Firefox 39.0 32-bit on Windows NT 6.3 64-bit, the a=[] is fastest !
5 年多之前 回复
weixin_41568184
叼花硬汉 Adding the percentage changes arent much use without also noting your platform. On my machine pop is only very mildly quicker in Chrome 34 but actually slower than [] in latest Firefox.
6 年多之前 回复

A.splice(0);

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

weixin_41568126
乱世@小熊 No you've just swapped a named array container with a newly created anonymous one. `var A = [1,2,3,4]; var B; B = A.splice(0); console.log(A); console.log(B); '
接近 4 年之前 回复

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)

weixin_41568126
乱世@小熊 It could be a good answer to a different question: "How to convert all elements in an array to undefined elements".
3 年多之前 回复

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:

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

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).

csdnceshi74
7*4 I can't believe nobody spotted that benchmark error. With over half a million views you would expect someone to notice it. Great work Diadistis
5 年多之前 回复
csdnceshi74
7*4 Very good point! I'll update the original answer with the correct benchmark results.
5 年多之前 回复

Use a modified version of Jan's initial suggestion:

var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
     A.pop();
}
csdnceshi65
larry*wei Why would you want to do such thing? Why add two more variables and a bunch of code to do the same thing?
大约 6 年之前 回复

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

public emptyFormArray(formArray:FormArray) {
    for (let i = formArray.controls.length - 1; i >= 0; i--) {
        formArray.removeAt(i);
    }
}
csdnceshi56
lrony* This is irrelevant and not even JavaScript.
大约 3 年之前 回复
共17条数据 首页 2
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐