这是我编程生涯中遇到的最奇怪的事情。
self.walls = new Array();
self.walls = [];
console.log(self.walls); //Doesn't print an empty array, but an array that contains something
这怎么可能?我通过两种方式将 self.walls
设置为一个空数组,它仍然充满了对象!我使用的是最新版本的谷歌浏览器。
编辑:另外,这是整个脚本中唯一的 console.log()
。
最佳答案
console.log
不存储对象在调用时的状态。
稍后,您覆盖了控制台中显示的 self.walls
属性。
如果想记录执行时的真实状态,可以序列化对象:
// Works for primitives only:
console.log(JSON.parse(JSON.stringify(self.walls)));
// When the array contains another object, the shown referenced object might
// change
console.log(self.walls.concat()); // Or any other array-copying method.
关于javascript - 清空数组在 javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9762165/