Shorter conditional or versus many line syntax

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 there is a shorter syntax for using "this.selectedItem.label" just one.

+5
source share
2 answers

Could it be an array and indexOf function?

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

This is a cross browser solution.

Good, includes (not tested in IE)

 if(["str1","str2","str3","str4"].includes(this.selectedItem.label)){ } 
+9
source
 if(["str1", "str2"].indexOf(this.selectedItem.label) !== -1) { // TO DO } 
+2
source

Source: https://habr.com/ru/post/1270916/


All Articles