我的问题与JavaScript中的循环引用有关。 基本上我正在尝试创建一个js数组并将相同的数组作为属性放在其自身内部。 当我在我的firebug控制台上尝试下面的代码时,我无法解释为什么会出现以下输出。
var a = [];
a[a]=a;
//delete(a[a[a[a]]]); edited
delete(a[a][a][a][a]);
console.log(a[a]);
//says undefined. but i deleted the 4th nested level ??
console.log(a);
//still gives []. so a exists.
我的问题是,我只删除了a[a][a][a][a]
,但外部属性应该保持正确吗?像a[a]
& a[a][a]
不应该是undefined
对吗?
但是当我将数组作为一个属性分配为自身并在firebug上检查相同时,我能够以嵌套的方式扩展对象的键和值,如果它获得为空的键,它应该是在检查员身上可见吗?
答案 0 :(得分:3)
a
作为财产。属性名称必须是JS中的字符串,当使用空数组作为属性名称时,它将自动将[]
字符串化为""
。你很幸运,字符串化没有考虑非数字属性。那会发生什么:
var a = [];
// OK an empty array.
a[a] = a;
a[""] = a;
// set the "" property of it to itself
delete(a[a[a[a ]]]);
delete a[a[a[a ]]]
delete a[a[a[""]]]
delete a[a[ a ]]
delete a[a[ "" ]]
delete a[ a ]
delete a[ "" ]
// remove the "" property from a
console.log(a[a]);
// is undefined now again
console.log(a);
// still gives []. Is still an array without any items.
请注意a[a][a][a] === a
所以当delete a[a][a][a][a]
delete a[a]
时,它只相当于a[""] = a;
// set the "" property of it to itself again
delete(a[""][""][""][""]);
delete a[""] [""] [""] [""]
delete (((a[""])[""])[""])[""]
delete (( a [""])[""])[""]
delete ( a [""])[""]
delete a [""]
// remove the "" property from a again
console.log(a[""]);
// is undefined now again
。您可以无限次地遵循循环引用,但只有一个引用存在然后被删除:
{{1}}
答案 1 :(得分:1)
发生的事情是这样的:
a
对自己有参考。a[a]
获取位于value
string value
a
的{{1}},该a
是对a[a[a]]
的引用。value
获取位于string value
结果的a[a]
的{{1}},该a
是对delete
的引用。所以你可以说没有真正的" 第4级"。
delete(a[a])
缩减为a[a][a][a][a] = a[a][a][a] = a[a][a] = a[a] = a;
。
<强>更新强>
由于
a[a]
因为a
返回[]
,您只需将a
运算符再次应用于delete(a[a][a][a][a]);
。
所以
delete(a[a]);
变为delete(a[""]);
,后者变为var a = [];
a[a] = a;
console.log(a); // has 1 element
console.log(a[a] == a); //true
console.log(a[a] === a); // true
console.log(a == ""); // true
a[a][a][a].push("1");
console.log(a); // has 2 elements
console.log(a[a]); // this becomes undefined because a is no more ""
var b = [];
b[b] = b;
b.push("1");
console.log(b);
console.log(b[b]);
console.log(b[b] == b);
更新2:
查看this fiddle。
{{1}}