admin管理员组文章数量:1180493
var arr = [-3, -34, 1, 32, -100];
How can I remove all items and just leave an empty array?
And is it a good idea to use this?
arr = [];
Thank you very much!
var arr = [-3, -34, 1, 32, -100];
How can I remove all items and just leave an empty array?
And is it a good idea to use this?
arr = [];
Thank you very much!
Share Improve this question edited Aug 27, 2010 at 16:18 John Kugelman 361k69 gold badges547 silver badges594 bronze badges asked Aug 27, 2010 at 16:16 qinHaiXiangqinHaiXiang 6,41912 gold badges48 silver badges61 bronze badges 3- 4 You answered your own question, at least the first one! – Stephen Commented Aug 27, 2010 at 16:17
- possible duplicate of How to empty an array in JavaScript? – Abid Rahman K Commented Apr 25, 2013 at 17:54
- 2 Possible duplicate of How do I empty an array in JavaScript? – Mohammad Usman Commented Nov 16, 2017 at 8:06
8 Answers
Reset to default 21If there are no other references to that array, then just create a new empty array over top of the old one:
array = [];
If you need to modify an existing array—if, for instance, there's a reference to that array stored elsewhere:
var array1 = [-3, -34, 1, 32, -100];
var array2 = array1;
// This.
array1.length = 0;
// Or this.
while (array1.length > 0) {
array1.pop();
}
// Now both are empty.
assert(array2.length == 0);
the simple, easy and safe way to do it is :
arr.length = 0;
making a new instance of array, redirects the reference to one another new instance, but didn't free old one.
These are the ways to empty an array in JavaScript
arr = [];
arr.splice(0, arr.length);
arr.length = 0;
one of those two:
var a = Array();
var a = [];
Just as you say:
arr = [];
Using arr = [];
to empty the array is far more efficient than doing something like looping and unsetting each key, or unsetting and then recreating the object.
Out of box idea:
while(arr.length) arr.pop();
Ways to clean/empty an array
- This is perfect if you do not have any references from other places. (substitution with a new array)
arr = []
- This Would not free up the objects in this array and may have memory implications. (setting prop length to 0)
arr.length = 0
- Remove all elements from an array and actually clean the original array. (splicing the whole array)
arr.splice(0,arr.length)
本文标签: How to empty an javascript arrayStack Overflow
版权声明:本文标题:How to empty an javascript array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738113848a2064628.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论