+ 6
Can I use (Switch/Case) statement for an array? (JavaScript)
I want to use Switch/Case statement for an array. For example : var arr = ["Item1","Item2", "Item3",......]; switch (arr) { case arr[0]: //print something break; case arr[1]: //print something break; case arr[2]: //print something break; } Is it possible? If possible, then what is the right way?
6 Antworten
+ 4
var arr = new Array("a", "b", "c");
var key = "b";
switch(key){
case arr[0]:
console.log("a");
break;
case arr[1]:
console.log("b");
break;
case arr[2]:
console.log("c");
break;
}
Code playground is self explanatory.
Do a code. And check if it works or not.
+ 3
Arb Rahim Badsa
Maybe your code will give an error because you used same arr in switch and case both.
My code will work for you as example.
+ 2
Raj Chhatrala I had tested the code. But it gave me an error. Btw thanks for your answer!
+ 2
An array may consist of multiple values and switch is able to perform equality checking at one value at a time.
Otherwise, a loop might be required.
Meanwhile, can you further elaborate on what are you trying to achieve with switch?
Because you've referred the array twice using switch in 2 different way and the switch statement can only evaluate a value inatead of an entire array.
+ 2
I think its possible
0
Notece:
!!(arr == arr[0]); // false
!!(arr == arr[1]); // false
!!(arr == arr[2]); // false
None case never will to be able to run.