0

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?

8
  • Is seat a string or an object? Commented Feb 24, 2019 at 14:23
  • Maybe console.log this.selectedSeats before calling indexOf on it will provide a clue 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 ? Commented Feb 24, 2019 at 14:23
  • @Jns it is an Integer 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? Commented Feb 24, 2019 at 14:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Also can't the OP just not use parentheses around the first part of the ternary?
Absolutely, leaving off the parens would also solve the problem.
Awesome! I'm starting write without semi-colons so I guess it was just a matter of time before I ran into this. Thanks.
@brunouno Better to always use semi-colons
There is a huge debate about that topic, and it all comes down to having a good understanding of ASI (Automatic Semicolon Insertion). This is a pretty good "opposing viewpoint" article, especially the line about: "If you 'never use semicolons', there’s only one rule: Never start a line with [, (, or `". (backtick because of tagged template literals)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.