Two ways to empty an array

Source: https://www.jstips.co/en/javascript/two-ways-to-empty-an-array/

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] []
  • 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.
In other words, if you have two references to the same array (a = [1,2,3]; a2 = a;), and you delete the array’s contents using list.length = 0, both references (a and a2) will now point to the same empty array. (So don’t use this technique if you don’t want a2 to hold an empty array!)
Think about what this will output:

Không có nhận xét nào:

Is it okay to use both fetchpriority="high" and loading="eager" in img tag?

 https://stackoverflow.com/questions/77744344/is-it-okay-to-use-both-fetchpriority-high-and-loading-eager-in-img-tag Yes Fetchpriority and l...