您的位置:首页 > Web前端 > JavaScript

Empty an Array

2016-01-25 14:02 441 查看
You define an array and want to empty its contents. Usually, you would do it like this:

// define Array
var list = [1, 2, 3, 4];
function empty() {
//empty your array
list = [];
}
empty();


But there is another way to empty an array that is more performant.

You should use code like this:

var list = [1, 2, 3, 4];
function empty() {
//empty your array
list.length = 0;
}
empty();


list = []
assigns a reference to a new array to a variable, while any other references are unaffected. which means that references to the contents of the previous array are still kept in memory, leading to memory leaks.

list.length = 0
deletes everything in the array, which does hit other references.

However, if you have a copy of the array (A and Copy-A), if you delete its contents using list.length = 0, the copy will also lose its contents.

Think about what will output:

var foo = [1,2,3];
var bar = [1,2,3];
var foo2 = foo;
var bar2 = bar;
foo = [];
bar.length = 0;
console.log(foo, bar, foo2, bar2);

// [] [] [1, 2, 3] []


from:github/loverajoel
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript 数组