Home  >  Q&A  >  body text

"TypeError ..undefined" in for loop

I'm using BootstrapVue.

What I want to do: I have a b-form-input in which I write a number. After my b-button is clicked, I want to add it to my inputs. This works great, but now I want to first check if my number is still in my inputs.

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

I have stated that everything in my data is correct and without for-loop it works fine. What's wrong here? I can't figure it out..

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

Thanks for trying to help me!

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,
        })
      }
    }
  }
},

P粉099145710P粉099145710206 days ago395

reply all(1)I'll reply

  • P粉421119778

    P粉4211197782024-03-27 12:29:11

    Using conditions i <= this.inputs.length You are exceeding the bounds of the array. In JavaScript, over-indexing an array returns undefined.

    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,
            })
          }
        }
      }
    },

    reply
    0
  • Cancelreply