简体   繁体   中英

JavaScript stops loop execution after push to array

I have a problem with simple script. I have a model called 'FeatureFlag' which is a tree structure with reference to parent and children. I have also object called TreeBuilder which makes a tree from a list of FeatureFlag elements.

Here is my model:

export class FeatureFlag {
    private _id: number;
    private _parent: FeatureFlag;
    private _children: FeatureFlag[] = [];

    set id(id:number) {
        this._id = id
    }

    set parent(parent:FeatureFlag) {
        this._parent = parent
    }

    get parent() : FeatureFlag {
        return this._parent
    } 

    set children(children:FeatureFlag[]) {
        this._children = children
    }

    get children() : FeatureFlag[] {
        return this._children
    }                       
}

and problematic method build() in TreeBuilder:

public build() {
    for(let element of this.data) { //this.data is an array of dict [{node,parent}]
        let found = this.findNode(element.parent) //searches in tree for node with id 'element.parent'

        if(found) { //if parent node has been found          
             //found.children.push(element.node) //add current node to its children
             console.log(found) //print found
         }           
    }
}

When line:

found.children.push(element.node)

is commented, console prints all found parents. It is ok. But when line is uncommented, console.log prints only once - a first found parent. Why is that happening?

Regards

Wierd! I would put a debugger statement before the push and then step through it to make sure it is not throwing an error that is silently getting caught. Also make sure that children.push does not have any unintended side affects.

I suspect that children.push is somehow throwing, perhaps because children is not defined, but Angular is swallowing the error. Also, is findNode for sure returning a FeatureFlag and not something else?

I encountered similar issue:

  var errors;
    let imput_email = $('#loginEmail').val().toUpperCase();
    if (!validateEmail(imput_email)){
        $( "#loginEmail + .invalid-feedback" ).addClass( "d-block" );
        console.log("I can see this in console");
        errors.push("Kiwi");
        console.log("NOTHING IN CONSOLE");
        alert("ALERT NOT WORKING EITHER");
    }
    if (!validatePass(imput_pass)){ // this part was working before push

What worked here is just initializing the errors variable:

  var errors= [];

I can understand that if the array is empty and it has no information that it is an array it is one of those "silent errors". Hope it helps someone despite the 4 years delay

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