+ 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?

27th Dec 2018, 12:24 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
6 Respuestas
+ 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.
27th Dec 2018, 12:32 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 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.
27th Dec 2018, 12:36 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
Raj Chhatrala I had tested the code. But it gave me an error. Btw thanks for your answer!
27th Dec 2018, 12:34 PM
Arb Rahim Badsa
Arb Rahim Badsa - avatar
+ 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.
27th Dec 2018, 12:39 PM
Zephyr Koo
Zephyr Koo - avatar
+ 2
I think its possible
28th Dec 2018, 9:54 AM
Sandakan Nipunajith
Sandakan Nipunajith - avatar
0
Notece: !!(arr == arr[0]); // false !!(arr == arr[1]); // false !!(arr == arr[2]); // false None case never will to be able to run.
5th Jan 2019, 11:48 AM
Mr Genesis
Mr Genesis - avatar