Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Difference between Array.length = 0 and Array =[]?

Can some one explain the conceptual difference between both of them. Read somewhere that the second one creates a new array by destroying all references to the existing array and the .length=0 just empties the array. But it didn't work in my case

//Declaration 
var arr = new Array();

The below one is the looping code that executes again and again.

$("#dummy").load("something.php",function(){
   arr.length =0;// expected to empty the array
   $("div").each(function(){
       arr = arr + $(this).html();
   });
});

But if I replace the code with arr =[] in place of arr.length=0 it works fine. Can anyone explain what's happening here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

foo = [] creates a new array and assigns a reference to it to a variable. Any other references are unaffected and still point to the original array.

foo.length = 0 modifies the array itself. If you access it via a different variable, then you still get the modified array.

Read somewhere that the second one creates a new array by destroying all references to the existing array

That is backwards. It creates a new array and doesn't destroy other references.

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

gives:

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

arr.length =0;// expected to empty the array

and it does empty the array, at least the first time. After the first time you do this:

arr = arr + $(this).html();

… which overwrites the array with a string.

The length property of a string is read-only, so assigning 0 to it has no effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...