Home > Enterprise >  "TypeError .. is undefined" in for loop
"TypeError .. is undefined" in for loop

Time:12-16

I'm working with BootstrapVue.

What I'm trying to do: I have a b-form-input where I write in a number in it. After clicking on my b-button I want to add this to my inputs. This works well but now I want to check first if my number is still in my inputs.

PROBLEM: After trying to add something to my inputs I always get following error: [Vue warn]: Error on v-on handler: "TypeError: this.inputs[i] is undefined"

I've declared everything correct in my data and without the for-loop it's working well. What is the error in here? I could not figure it out..

also when I try to do this: this.inputs[0].number i get the correct data..

Thanks for trying helping me out!

Code in my template:

<b-form-input v-model="number"></b-form-input>
<b-button @click="addSomething(number)"></b-button>

Code in my script:

addSomething(number) {
  if(this.inputs != []) {
    for(let i = 0; i <= this.inputs.length; i  ) {
      if(number === this.inputs[i].number) {
        console.log("Still existing!");
      } else if(number !== this.inputs[i].number) {
        this.inputs.push({
          INPUT_NUMBER: number,
        })
      }
    }
  }
},

CodePudding user response:

With the condition i <= this.inputs.length you are running over your array's bounds. In JavaScript overindexing an array returns undefined.

The fixed handler should be:

addSomething(number) {
  if(this.inputs != []) {
    for(let i = 0; i < this.inputs.length; i  ) {
      if(number === this.inputs[i].number) {
        console.log("Still existing!");
      } else if(number !== this.inputs[i].number) {
        this.inputs.push({
          INPUT_NUMBER: number,
        })
      }
    }
  }
},
  • Related