简体   繁体   中英

Changing the variables of a class in OOP in javascript

I have defined a function called Node which stores the properties of nodes in a graph data structure. The function is something like this:

function Node(){
    ...
    this.outEdges = [];
    this.inEdges = [];
    ...
}

where the inEdges and outEdges store elements of type Edge which is another function I have defined. During the program these arrays are filled with elements.

At some point in my code I need to reset these two arrays so I write:

    nodes[i].outEdges.length = 0;
    nodes[i].inEdges.length = 0;

where nodes is an array of elements of type Node and I am accessing an element in a for loop.

The problem is, after setting outEdges and inEdges to 0, I expected them to be [] in the nodes[i] property list. However, when I output nodes[i] into console, the outEdges and inEdges still have the elements in them. The stranger thing is that when I output nodes[i].outEdges to console, it prints [] , which is correct, but clicking on [ ] again opens the list of the elements! I can't really figure out why the nodes[i] variables don't change?

That happens (probably) because the browser prints out the empty array but by the time you check it, it has content again. So when you click to expand the browser shows the actual content. 在此处输入图片说明

As you can see the values [1,3,7] were added after the command console.log(o) but they are shown on the screen (even though the length shown is 0 ).

You're not supposed to set the length field. Just re-initialize them:

nodes[i].outEdges = [];
nodes[i].inEdges = [];

Edit: My bad, setting the length should work. It does work for me on Chrome at least. However, I still think it's safer and better style to re-init.

只需创建一个具有相同名称的新对象

nodes[i].outEdges = new Array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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