0

Does this not work? I thought that this was valid, but it isn't working.

var items = ["image", "text"];
console.log(this.type)
if(this.type in items){
    console.log("here")
}

console.log(this.type) displays image, but here is never displayed.

Am I doing something wrong, or am I thinking of the wrong language?

1
  • You must specify index number not value. Commented Apr 30, 2015 at 17:20

3 Answers 3

8

in checks among the property names of the object.

Here, what you need is indexOf:

if (~items.indexOf(this.type)){

Note: this is a short version for

if (items.indexOf(this.type)!==-1){

using the bitwise not operator.

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

Comments

0

You can do

var items = ["image", "text"];
var item = "image";
if (items.indexOf(item) > -1) {
  console.log("here");
}

Array.indexOf() MDN

Comments

0

The "in" keyword in JavaScript only works for keys and properties of objects. The way I would do this:

if (items.indexOf(this.type) !== -1)

This will return the index of the type you're looking for or -1 if it's not there. If it's not equal to -1, then it's there.

Comments

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.