Ank*_*kan 1 javascript firebug
我正在运行此代码并检查firebug中的日志:
var a = new Array();
var b = new Array();
for (i=0; i<2 ; i++){
a.push(1);
b.push(a);
console.log("a", a);
console.log("b", b);
};
Run Code Online (Sandbox Code Playgroud)
日志显示以下值:
a [1]
b [[1]]
a [1,1]
b [[1,1],[1,1]]
Run Code Online (Sandbox Code Playgroud)
据我说,价值应该是:
a [1]
b [[1]]
a [1,1]
b [[1],[1,1]]
Run Code Online (Sandbox Code Playgroud)
我做错了什么,我怎么能得到我想要的价值?
当您使用.push追加a到末尾时b,您传递的是引用,而不是ByVal,因为Array是一个Object.这意味着未来的变化将a反映在a已经存在的s中b.你需要的是什么时候去..slice a.pushb
var a = new Array(), b = new Array();
for (i=0; i<2 ; i++) {
a.push(1);
b.push(a.slice());
console.log("a", a);
console.log("b", b);
};
/*
a [1]
b [[1]]
a [1, 1]
b [[1], [1, 1]]
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |