清空数组的两种方法
如果你定义了一个数组,然后你想清空它。 通常,你会这样做:
// 定义一个数组
var list = [1, 2, 3, 4];
function empty() {
//清空数组
list = [];
}
empty();
但是,这有一个效率更高的方法来清空数组。 你可以这样写:
var list = [1, 2, 3, 4];
function empty() {
//empty your array
list.length = 0;
}
empty();
-
list = []
将一个新的数组的引用赋值给变量,其他引用并不受影响。 这意味着以前数组的内容被引用的话将依旧存在于内存中,这将导致内存泄漏。 -
list.length = 0
删除数组里的所有内容,也将影响到其他引用。
然而,如果你复制了一个数组(A 和 Copy-A),如果你用list.length = 0
清空了它的内容,复制的数组也会清空它的内容。
考虑一下将会输出什么:
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] []
更多内容请看Stackoverflow: difference-between-array-length-0-and-array
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW