Array.length = 0 和 Array =[] 的区别? [英] Difference between Array.length = 0 and Array =[]?
问题描述
有人可以解释一下两者在概念上的区别吗?在某处读到第二个通过销毁对现有数组的所有引用来创建一个新数组,而 .length=0 只是清空数组.但它在我的情况下不起作用
//声明var arr = new Array();
下面一段是反复执行的循环代码.
$("#dummy").load("something.php",function(){arr.length =0;//期望清空数组$("div").each(function(){arr = arr + $(this).html();});});
但是如果我用 arr =[]
代替 arr.length=0
替换代码,它工作正常.谁能解释一下这里发生了什么.
foo = []
创建一个新数组并将对它的引用分配给一个变量.任何其他引用不受影响,仍指向原始数组.
foo.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] []
<小时><块引用>
arr.length =0;//期望清空数组
它确实清空了数组,至少在第一次是这样.在您第一次这样做之后:
<块引用>arr = arr + $(this).html();
...用字符串覆盖数组.
字符串的 length
属性是只读的,所以给它赋值 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();
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.
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.
这篇关于Array.length = 0 和 Array =[] 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!