user10109757
user10109757

Reputation:

Cannot read property length

I have a method here where i am taking length of an array in a loop and i am kind of confused because this error occurs only sometimes and not always. Sometimes i am able to get the filtered values in my textbox while sometimes i am unable to i tried removing set timeout too but whenever i face this error it does not show me filteredNames. why is this happening?

SubName(subjec: string[], compar: string[]) {
  setTimeout(() => {
    this.len = subjec.length;
    this.len2 = compar.length;
    this.filteredName = [];
    for(var i = 0; i< this.len; i++) {
      if(compar.indexOf(subjec[i]) === -1){
        this.filteredName.push(subjec[i]);
      }
    }
    for(var j = 0; j<this.len2; j++) {
      if(subjec.indexOf(compar[j]) === -1){
        this.filteredName.push(compar[j]);
      }
    }
    console.log("Names = " + this.filteredName);
    return this.filteredName;
  }, 500);
}

Upvotes: 0

Views: 90

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27303

You can get rid of that error by using ternary operator

SubName(subjec: string[], compar: string[]) {
setTimeout(() => {
this.len = subjec== undefined ? subjec : subjec.length;
this.len2 = compar== undefined ? compar: compar.length;
this.filteredName = [];
for(var i = 0; i< this.len; i++) {
  if(compar.indexOf(subjec[i]) === -1){
    this.filteredName.push(subjec[i]);
  }
}
for(var j = 0; j<this.len2; j++) {
  if(subjec.indexOf(compar[j]) === -1){
    this.filteredName.push(compar[j]);
  }
}
console.log("Names = " + this.filteredName);
return this.filteredName;
},500);
}

Upvotes: 2

Related Questions