1

I have following code snippet:

console.log('**1**',parentNode.child.length); //1
            for(var ch in parentNode.child)
            {
                console.log('PTree root child',parentNode.child[ch]); //2
            }

In //1 parentNode.child.length comes out to be 0 but still it goes inside the for loop and gives following output in line //2:

PTree root child (val) {
        if (this.indexOf(val) === -1) {
            this.push(val);
        }

        return this;
    }

I am not sure why it is happening.

1 Answers1

1

I assume parentNode.child is array. So, here are the possibilities which could cause this.

  1. That array has a non-numeric named property.

var data = [];
data.someFunc = function(){};
console.log("length: %s", data.length);
for(var key in data) console.log("%s: %s",key, data[key]);
  1. You monkey-patched Array.prototype somehow.

Array.prototype.coolFunc = function(){ return "cool" };
var data = [];
console.log("length: %s", data.length);
for(var key in data) console.log("%s: %s", key, data[key]);

So, to avoid this simply use forEach

var data = [];
data.someFunc = function(){};
console.log("length: %s", data.length);
data.forEach(item => console.log(item));
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28