Walter White Walter White - 2 years ago 90
Javascript Question

Shorter syntax of conditional or against many Strings

I have something like this:

if(this.selectedItem.label == "str1"
|| this.selectedItem.label == "str2"
|| this.selectedItem.label == "str3"
|| this.selectedItem.label == "str4") {
}


I wonder if exist shorter syntax to use "this.selectedItem.label" only one.

Answer Source

May be array and indexOf function ?

if(["str1","str2","str3","str4"].indexOf(this.selectedItem.label) > -1){
  // found
}

That's a cross browser solution.

Oh well, includes (haven't tested in IE)

if(["str1","str2","str3","str4"].includes(this.selectedItem.label)){

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download