如何清空 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个回答

Ways to clear an existing array A:

Method 1

(this was my original answer to the question)

A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.

This is also the fastest solution.

This code sample shows the issue you can encounter when using this method:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

Method 2 (as suggested by Matthew Crumley)

A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.

Method 3 (as suggested by Anthony)

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.

Method 4 (as suggested by tanguy_k)

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.

Performance

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.

As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.

The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).


This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;
csdnceshi78
程序go Thanks for getting back to me. I use Typescript and in the meantime I realized that the array what I use has a custom type, thus 0-ing out the length property did not erase the content of the array. I had instead a clear() method.
接近 3 年之前 回复
csdnceshi62
csdnceshi62 I'm not sure what you mean. It shouldn't care what type of values are in the array.
接近 3 年之前 回复
csdnceshi78
程序go setting length to 0 does not work when i have an array of objects
接近 3 年之前 回复
csdnceshi67
bug^君 In ES6 you want to use const instead var making the new init less helpful. The const arr.lenth = 0 is very quick. jsben.ch/oZr0V
大约 3 年之前 回复
csdnceshi62
csdnceshi62 That's what setting the length already does. Each reference is pointing to the same object in memory, so setting the length on one reference will affect all of them.
3 年多之前 回复
weixin_41568134
MAO-EYE how to update it so that it makes the length=0 in all the references?
3 年多之前 回复
csdnceshi52
妄徒之命 .length = 0 does work in my case, but we get back to your comment about garbage collection. I am instead opting for iterating to execute all my functions, and then iterating again to pop after. .length = 0; It would have been better if we would have clear method so folks don't have to get into all kind of issues depending on use case. This entire thread and discussion with over 5000 votes is a testament to that :)
大约 4 年之前 回复
csdnceshi52
妄徒之命 You last comment, "the old allocated space would be more efficient and reduce GC pressure." - That's my point, is that .lenght = 0; you do not actually free up the memory. In my use case, I am iterating all elements from first to end, they are functions and once executed they can be removed. Since adjusting the array for each iteration is costly, especially from the beggining to end, I want to clear the array at the end of the iteration of all. I am calling a method with the array to iterate, so setting array = [] won't work. I need to actually empty the array.
大约 4 年之前 回复
csdnceshi62
csdnceshi62 (continued) If you want to guarantee the array is as compact as possible at the end, you would need to create a new array and leave the old one to be garbage collected (assuming you're not sharing the array, in which case that's not an option). Whether that's beneficial or not depends on the exact use case. For example, if you're going to be filling in the array again, then reusing the old allocated space would be more efficient and reduce GC pressure.
大约 4 年之前 回复
csdnceshi62
csdnceshi62 Popping elements off the array is likely to have the same effect in terms of memory. There's nothing in the spec that requires implementations to adjust the amount of space allocated to the array, but as far as I know, they will all reduce the size once the length gets below some threshold.
大约 4 年之前 回复
csdnceshi52
妄徒之命 Yes, the garbage collection issue is exactly why I am in here. To me there is no way of knowing what kind of magic and special logic is executed by setting this value to zero, especially when it is not even a method call. I do not know what the implementors are actually handling it and that's too much magic. I will be popping, and I think it is even faster. Maybe faster than popping is setting each to undefined, so nothing has to be loaded into memory ( return value) . That way I am in control.
大约 4 年之前 回复
csdnceshi62
csdnceshi62 Deleting the elements above the new length is required by the ECMAScript spec, so any correct implementation will make any inaccessible elements garbage collectible. That doesn't necessarily mean they will shrink the storage for the actual array immediately. Specifically, V8 only re-allocates the array if the new length is less than half of the original length, but setting the length to zero essentially re-allocates a new array behind the scenes.
大约 5 年之前 回复
csdnceshi80
胖鸭 Are we certain that this method of setting the length to 0 gets rid of references to the unwanted array elements? Intuitively, it seems to me that the references are still somewhere inside the array object. They will probably be overwritten by other array elements but it looks like setting it to 0 never really allows the GC to collect the rest and that unwanted memory is blocked from use by everything except the original array. Maybe they have some logic built in for this problem? I'd love for someone to explain.
大约 5 年之前 回复
csdnceshi63
elliott.david True, by calling those you do not invalidate the references. I still like length = 0 opposing to ref.splice(0, ref.length)
5 年多之前 回复
csdnceshi51
旧行李 It's not the only way. The splice() and pop() methods also don't invalidate other references.
5 年多之前 回复
csdnceshi72
谁还没个明天 I done some test, and it seems like a.length = 0 is not to efficient clearing whole array. jsperf.com/length-equal-0-or-new-array I think if you have one refence (and you haven't added extra properties that you want to keep), it is better to create new array, and leaves old to the garbage collector, that will run when appropriate.
接近 7 年之前 回复
csdnceshi72
谁还没个明天 "If you need to keep the original array because you have other references to it that should be updated too," If I don't have any other references, is it still best method ?
接近 7 年之前 回复
csdnceshi53
Lotus@ Keep in mind, if you create a new array, the GC will take care of the old one later in time, too! So we can say arr.length = 0; = GC immediately and arr = []; = GC later on
大约 7 年之前 回复
weixin_41568131
10.24 Thanks for the reference. So, who will delete the array elements? Garbage collector?
大约 7 年之前 回复
weixin_41568131
10.24 does it mean that, it corrects the length automatically?
大约 7 年之前 回复
csdnceshi61
derek5. Don't use this approach when creating elements dynamically within for loop(which was my situation).. go with PhilippeLeybaert post instead.
7 年多之前 回复
csdnceshi60
℡Wang Yan As a serious developer I am not sure without being able to reproduce it and not even then...
接近 8 年之前 回复
csdnceshi62
csdnceshi62 That seems wrong to me. Are you sure it was an array, and not a NodeList or other array-like object? I think the length property would be read only in that case.
接近 8 年之前 回复
csdnceshi60
℡Wang Yan I tried it in IE10 desktop mode in Win8 - it doesn't work. Can't remember the exact wording of the message - possibly something along the wording of my original comment.
接近 8 年之前 回复
csdnceshi62
csdnceshi62 Even in strict mode, length is a special property, but not read only, so it will still work.
接近 8 年之前 回复
csdnceshi60
℡Wang Yan If you use "use strict"; it will not work. Setting a readonly parameter is not allowed. stackoverflow.com/questions/1335851/…
接近 8 年之前 回复
csdnceshi62
csdnceshi62 It shouldn't in a correctly-implemented interpreter, and I don't know of any implementations that do. OF course, it's possible but it's not any more likely than other incorrect sources of leaks.
8 年多之前 回复
weixin_41568208
北城已荒凉 Would this solution cause/make it possible for a memory leak? Obviously, this depends on the JS interpreter, but it seems like something that could lead to a leak...
8 年多之前 回复
csdnceshi62
csdnceshi62 JavaScript arrays always expand to fit whatever you put in them, so when you call myarray.push(whatever) it adds one to the length. So setting the length truncates the array, but it's not permanent.
大约 9 年之前 回复
csdnceshi62
csdnceshi62 It still works in ES5. From section 15.4: "...whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted"
9 年多之前 回复
csdnceshi56
lrony* what does ECMAScript 5 Standard says about this?
9 年多之前 回复
csdnceshi62
csdnceshi62 Yes, it will work in all browsers.
9 年多之前 回复
csdnceshi58
Didn"t forge Should this work with all browsers?
9 年多之前 回复

Here the fastest working implementation while keeping the same array ("mutable"):

Array.prototype.clear = function() {
  while (this.length) {
    this.pop();
  }
};

FYI Map defines clear() so it would seem logical to have clear() for Array too.

Or as an Underscore.js mixin:

_.mixin({
  clearArray: function(array) {
    while (array.length) {
      array.pop();
    }
  }
});

Or a simple function:

function clearArray(array) {
  while (array.length) {
    array.pop();
  }
}

TypeScript version:

function clearArray<T>(array: T[]) {
  while (array.length) {
    array.pop();
  }
}

FYI it cannot be simplified to while (array.pop()): the tests will fail.

And the tests that goes with it:

describe('Array', () => {
  it('should clear the array', () => {
    let array = [1, 2, 3, 4, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);

    // Even with undefined or null inside
    array = [1, undefined, 3, null, 5];
    array.clear();
    expect(array.length).toEqual(0);
    expect(array[0]).toEqual(undefined);
    expect(array[4]).toEqual(undefined);
  });
});

Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152

csdnceshi58
Didn"t forge we should also check the memory occupied before and after each test. And also check that the array is really empty. Anyway, array.length = 0 seems to be the best path.
5 年多之前 回复
weixin_41568184
叼花硬汉 It turns out this method is a lot slower than .splice() and .length=0. The benchmarks were not correct. See my updated answer.
5 年多之前 回复
csdnceshi60
℡Wang Yan This benchmark moves array population inside each test. Clearing the array quickly with .pop() might not be an overall optimization if it slows down creation of the next one.
接近 6 年之前 回复
weixin_41568126
乱世@小熊 I'd say, creating new methods for default objects is perfectly fine as long as it has some unique name. For example, I do so by prepending my nickname to it, and this is not limited with this example.
大约 6 年之前 回复
csdnceshi52
妄徒之命 What about memory usage? I read that behind the scenes length=0 is deleting all elements in the array. Is the speed coming with a larger memory cost in this case? 10x
6 年多之前 回复
csdnceshi51
旧行李 The whole point of not modifying global scope is because you won't know if someone else's code is already (or will be) using the name. I suggest a function inside local scope. So, inside your application's/library's IIFE, do function clear(arr) { while(arr.length) arr.pop(); }, then clear arrays with clear(arr) instead of arr.clear().
大约 7 年之前 回复
csdnceshi69
YaoRaoLov So what do you suggest? Its okay to add unless there is a function by the name already exists?
大约 7 年之前 回复
csdnceshi51
旧行李 you should not modify native objects. Saying that it should be there is beside the point, the problem is you're modifying globals, which is bad. If you're providing your code for others to use, then it should have no unforeseen side effects. Imagine if another library also modified the Array.prototype and it was doing something slightly different, then all throughout your code [].clear() was slightly wrong. This would not be fun to debug. So, the general message is: Don't modify globals.
大约 7 年之前 回复
csdnceshi69
YaoRaoLov But this is one of the basic functionalities, which should have been there by default.
大约 7 年之前 回复
csdnceshi57
perhaps? TT your answer is the only one that correct and fast ( at the same time ) but have some much less "upvotes". Well, it seems that people like pretty solutions that are slow :/
7 年多之前 回复

A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:

A.splice(0, A.length);

csdnceshi65
larry*wei not bad! A.splice(0) comes out 3rd out of the 6 methods! See jsben.ch/#/vtDS2 (derived from jsben.ch/#/hyj65 - head-to-head with "new init" is here: jsben.ch/#/3Do76)
接近 4 年之前 回复
weixin_41568174
from.. I have also found that just A.splice(0) also works.
接近 6 年之前 回复
csdnceshi60
℡Wang Yan splice is also incredibly slow as compared to other methods jsperf.com/array-splice-vs-array-length-0/2
接近 7 年之前 回复
csdnceshi72
谁还没个明天 We could prevent the resulting array from being returned by using the comma operator: A.splice(0, A.length),0;. This would leave a return value of 0 just as A.length = 0; would. The resulting array is still created and should cause the script to run slower: (jsperf ~56% slower). Browser implementation will affect this although I see no reason why splice would be faster than setting length.
大约 7 年之前 回复
csdnceshi62
csdnceshi62 Don't know why I wrote that. I must have missed the p and confused it with slice().
接近 8 年之前 回复
csdnceshi68
local-host no it does not, splice modifies the array and returns the deleted entries. Read the docs first: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
接近 8 年之前 回复
csdnceshi52
妄徒之命 what you are saying is not entirely true. It actually modifies the array in question and subsequently all references get affected. See the test on my jsFiddle: jsfiddle.net/shamasis/dG4PH
大约 8 年之前 回复
csdnceshi52
妄徒之命 This is the most correct answer since this actually "clears the array content and retains the reference to the original array object.
8 年多之前 回复
weixin_41568131
10.24 Like @alex said, splice returns a new array. Not something you would want to do in a REPL. You could always void the expression but that's not an elegant solution.
8 年多之前 回复
weixin_41568126
乱世@小熊 Why is this more cross-browser friendly? What browsers have issues with A.length?
接近 9 年之前 回复

The answers that have no less that 2739 upvotes by now are misleading and incorrect.

The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].

  1. Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.

    This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.


Let's say your mother asks you to empty the trash can.

  • You don't bring in a new one as if you've done what you've been asked for.
  • Instead, you empty the trash can.
  • You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in 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.

csdnceshi75
衫裤跑路 I loved the metaphors with the real world in this answer. Impressive!
2 年多之前 回复
csdnceshi50
三生石@ I agree with ghego1, other answers may be more upvoted, but this one is by far the best, because it explains the whys and whynots. Also, testing (jsben.ch/Rh0nb) shows that trusting the browser's internal garbage collection is always better (the splice(0), splice(0,length) and length=0 alternate first places on successive runs).
2 年多之前 回复
csdnceshi54
hurriedly% upvoted as your answer is by far the nicest and simplest explanation of why solutions other then A.length = 0 are inappropriate. I wish I could upvote more!!
3 年多之前 回复
csdnceshi69
YaoRaoLov there's only one way to empty your array fill it with new incoming data and discard it again. All others are either not, or are ridiculously inefficient and unforgivably cpu hungry. The only practical alternative is the A(n) = A.splice( 0, A.length ); in case you need to backup your previous content. p.s. Array.length is a read-write property \ method in case you've missed that basic fact. Meaning, you can expand it to a new length, you cant trim it to whichever length you'd want, and among others you can discard all members by shortening its length to 0. It's a Swiss-knife of the array.
大约 4 年之前 回复
csdnceshi57
perhaps? Therefore, I'd rather clear it myself. A clear method can be prototyped but that is just ugly. My point is that this implementation should already be present so that over 10 000 developers didn't have to spend hours reading just this thread, not considering all others who spent more time benchmarking.
大约 4 年之前 回复
csdnceshi57
perhaps? Because to accomplish what it should, all references must be removed. .length = 0 is not even a method call, so if there is other actions taken when it is set to 0 ( which there is in most browsers through define setter ) I would still consider it too magical to actually trust it does what it supposed to do.
大约 4 年之前 回复
csdnceshi57
perhaps? I never stated that this solution is wrong. The problem is that this entire thread is completely unncessary. Over 3000 votes shows that trying to figure out what the best way is should make it a valid enough case for the EMCA crack head developers to add such a method. Nobody should have to go through figuring it out. There are three - four different ways to do it. In some benchmarks, the length solutions is much slower than others. Furthermore, the idea of setting .length = 0, for any reasonable developer would not be a satisfactory one.
大约 4 年之前 回复
csdnceshi69
YaoRaoLov No sun, that's not true at all. You might wish to test things and understand them deep enough before trying to object something as rock solid as this core JavaScript functionality basics. And it's not "my solution" it's the basic JS syntax since forever. Dubious as it may be A.length = 0; is the standard syntax to empty your array. If you wish to have a method such as A.clear, you can use this standard syntax to add that method to your arrays easily: Array.prototype.clear = function(){this.length = 0}. Have fun.
大约 4 年之前 回复
csdnceshi57
perhaps? The only problem with your suggested solution is that the trash still exists, it is just that you changed the notice board saying that there is no trash. A reference to the old array should still exist. Can you be sure the garbage collector when setting .length = 0, will also remove all references to the array and its properties ? I think it does though, but to me that is magic. A .clear() method is desirable to avoid confusion to say the least.
大约 4 年之前 回复

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 年多之前 回复

You can add this to your JavaScript file to allow your arrays to be "cleared":

Array.prototype.clear = function() {
    this.splice(0, this.length);
};

Then you can use it like this:

var list = [1, 2, 3];
list.clear();

Or if you want to be sure you don't destroy something:

if (!Array.prototype.clear) {
    Array.prototype.clear = function() {
       this.splice(0, this.length);
    };
}

Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.

csdnceshi67
bug^君 As a reference: Why is extending native objects a bad practice?
大约 3 年之前 回复
csdnceshi73
喵-见缝插针 How about the problem where doing a foreach over the members of an array will suddenly start including a clear key?
大约 5 年之前 回复
csdnceshi70
笑故挽风 It is "frowned upon" to modify javascript primitive functions like Array and String. You could possibly be overloading an already existing function and trash the object class. There might be an obscure javascript engine that already has clear() and expects it to behave a different way. Tread carefully is all I say.
6 年多之前 回复
csdnceshi80
胖鸭 Can you explain your reasoning why doing such a thing is frowned upon?
大约 7 年之前 回复
Array.prototype.clear = function() {
    this.length = 0;
};

And call it: array.clear();

csdnceshi57
perhaps? I don't agree. Adding prototypes to native objects is a bad practice. Look at @EmileBergeron link as to why.
2 年多之前 回复
csdnceshi67
bug^君 As a reference: Why is extending native objects a bad practice?
大约 3 年之前 回复
weixin_41568110
七度&光 I actually have answers that give the exact opposite advice, but of course with the added context. It is my responsibility to communicate as effectively as possible, but I'm also okay with being misunderstood. I don't always have the time to provide citations and references for everything I say, and that's okay too. With answers like these (nothing but a snippet of code and zero explanation) I feel obligated to help push in the other direction to let readers know a particular answer doesn't stand unopposed – even if that effort is only slightly greater than the answer.
接近 4 年之前 回复
csdnceshi59
ℙℕℤℝ "Please don't encourage modification of the native objects." -- I completely agree with this, but just repeating the sentence by itself comes across as arrogant. Someone proposing such a solution is likely not aware of the consequences, and dropping this line on them instead of providing a short explanation or a link does not convey a meaning other than "we, people smarter than you, tell you not to do this, because we know better".
接近 4 年之前 回复
weixin_41568110
七度&光 my response would have to come in a long-form answer that has probably been said by hundreds of others. If you're curious, do some googling for "javascript don't modify native" or something. If you still have questions, ask a new question.
4 年多之前 回复
csdnceshi56
lrony* How could this get any upvote? No browser I know allows this = ... EDIT: I see, answer was different in previous versions.
接近 6 年之前 回复
weixin_41568208
北城已荒凉 PLEASE hackers / developers .... don`t mod things, where would that get us .
6 年多之前 回复
csdnceshi76
斗士狗 Why not just type array.length = 0?
6 年多之前 回复
csdnceshi69
YaoRaoLov why do people have this tendency to grab the accepted answer and put it into a prototype function? Do you actually do this in your projects? Do you have a huge library of prototype additions that you include in every project?
接近 7 年之前 回复
weixin_41568110
七度&光 Please don't encourage modification of the native objects.
7 年多之前 回复

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 年多之前 回复

In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in @tanguy_k's answer above.

(for an intro to the aforementioned tab you can check out here)

Stackoverflow forces me to copy the jsfiddle so here it is:

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

And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.

共17条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问