Array.length = 0和阵列之间差异= []? [英] Difference between Array.length = 0 and Array =[]?
问题描述
有人能解释一下两者之间的概念上的差异。读的地方,第二个通过破坏所有引用现有的阵列和。长度创建新的数组= 0只清空数组。但是,这并不在我的情况下工作。
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();
下面一个是循环code,它一次又一次地执行。
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();
});
});
但是,如果我更换code ARR = []
代替 arr.length = 0
它工作正常。任何人能解释这里发生了什么。
But if I replace the code with arr =[]
in place of arr.length=0
it works fine. Can anyone explain what's happening here.
推荐答案
富= []
分配给新的数组变量的引用,而其他任何引用不受影响。
foo = []
assigns a reference to a new array to a variable, while any other references are unaffected.
foo.length = 0
删除阵列,它不打其他文献中的一切。
foo.length = 0
deletes everything in the array, which does hit other references.
某处阅读第二个通过破坏现有阵列的所有引用创建新的数组
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);
给出了:
[] [] [1, 2, 3] []
这篇关于Array.length = 0和阵列之间差异= []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!