简体   繁体   English

清空数组在javascript中不起作用

[英]Emptying an array doesn't work in javascript

This is the weirdest thing I've ever encountered in my programming life. 这是我在编程生涯中遇到过的最奇怪的事情。

self.walls = new Array();
self.walls = [];
console.log(self.walls); //Doesn't print an empty array, but an array that contains something

How is this possible? 这怎么可能? I set self.walls to an empty array in two ways, and it's still full of objects! 我以两种方式将self.walls设置为一个空数组,它仍然充满了对象! I'm using the latest version of Google Chrome. 我正在使用最新版本的Google Chrome。

Edit: also, this is the only console.log() in the entire script. 编辑:此外,这是整个脚本中唯一的console.log()

console.log does not store the state of the object at the time of calling. console.log在调用时不存储对象的状态。
At a later point, you've overwritten the self.walls property, which is shown in the console. 稍后,您已经覆盖了self.walls属性,该属性显示在控制台中。

If you want to log the true state at the time of executing, you can serialize the object: 如果要在执行时记录真实状态,可以序列化对象:

// 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.

An array has a length , it has methods such as map , shift , unshift , pop , push and so on, and all of these show up in the console because they are properties of the array. 数组有一个length ,它有mapshiftunshiftpoppush等方法,所有这些都显示在控制台中,因为它们是数组的属性。

You probably don't see any property named 0 , 1 , or any other number, right? 你可能看不到任何名为财产01 ,或任何其他数量的,对不对? Those would be the actual array elements, if you'd defined any. 如果您定义了任何数组元素,那将是实际的数组元素。

As Rob W explained , the console sometimes does not show the true representation of the array when it is called. 正如Rob W所解释的那样console在调用时有时不会显示数组的真实表示。

However, you mentioned emptying an array but your code ... 但是,你提到清空数组但你的代码......

self.walls = new Array();
self.walls = [];

...is not emptying the array. ... 没有清空数组。 It is assigning a new empty array to the property. 它正在为属性分配一个新的空数组。 To empty the array, you can use... 要清空阵列,您可以使用...

self.walls.length = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM