admin管理员组

文章数量:1426072

I'm trying to check if a number is present in an array (which I've done a thousand times before using .indexOf()) but I seem to be missing something now.

Vue method

showSeat(seat) {
    if( !this.selectedSeats.length ) { 
        this.selectedSeats.push(seat)
    } else {
        let index = this.selectedSeats.indexOf(seat)
        ( index >= 0 ) ? this.selectedSeats.splice(index,1) : this.selectedSeats.push(seat)
    }
}

Initially, this.selectedSeats is equal to [], and the first condition runs perfectly. However, when I try to add another seat, I get [Vue warn]: Error in event handler for "showSeat": "TypeError: this.selectedSeats.indexOf(...) is not a function". What am I missing?

I'm trying to check if a number is present in an array (which I've done a thousand times before using .indexOf()) but I seem to be missing something now.

Vue method

showSeat(seat) {
    if( !this.selectedSeats.length ) { 
        this.selectedSeats.push(seat)
    } else {
        let index = this.selectedSeats.indexOf(seat)
        ( index >= 0 ) ? this.selectedSeats.splice(index,1) : this.selectedSeats.push(seat)
    }
}

Initially, this.selectedSeats is equal to [], and the first condition runs perfectly. However, when I try to add another seat, I get [Vue warn]: Error in event handler for "showSeat": "TypeError: this.selectedSeats.indexOf(...) is not a function". What am I missing?

Share Improve this question asked Feb 24, 2019 at 14:18 brunounobrunouno 5959 silver badges25 bronze badges 8
  • Is seat a string or an object? – Jns Commented Feb 24, 2019 at 14:23
  • Maybe console.log this.selectedSeats before calling indexOf on it will provide a clue – Dexygen Commented Feb 24, 2019 at 14:23
  • well, from the error, I can only assume that this.selectedSeats is not an array. What do you get if you do console.log(Array.isArray(this.selectedSeats)); before let index ? – Nick Parsons Commented Feb 24, 2019 at 14:23
  • @Jns it is an Integer – brunouno Commented Feb 24, 2019 at 14:23
  • 2 How about logging this.selectedSeats.indexOf (should be a native function). Also, is showSeats asynchronous? Maybe some more (but not too much) code for context? A jsfiddle or something? – Dexygen Commented Feb 24, 2019 at 14:30
 |  Show 3 more ments

1 Answer 1

Reset to default 4

This is one of those rare cases in JavaScript where leaving off a semicolon can cause huge problems. These two lines are being evaluated as a single expression:

 let index = this.selectedSeats.indexOf(seat)
 ( index >= 0 ) ? this.selectedSeats.splice(index,1) : this.selectedSeats.push(seat)

It's trying to execute this.selectedSeats.indexOf(seat)(index>=0)

Add a semicolon at the end of your indexOf(seat); and you should be fine.

本文标签: javascriptVue JSindexOf array is not a functionStack Overflow