Alternative for long if..else / switch chain in javascript

var ifChecks = function( i ) { if( i === 23 ) { // implementation } else if ( i === 300 ) { // implementation } else if ... } 

I have such a long one, if there is still a chain (application check 60) in javascript code, this long chain is ineffective, as if the 60th check was included as input, then it should pass 59 checks without need, so I decided to implement like this.

  var implobj = { 23 : handleimpl1, 300 : handleimpl2, . . . } var handleImpl = function( i ) { implobj[i](); } 

Is there any other way better than this solution that can be implemented in javascript?

Note: the input is not a sequential number, otherwise I could use an array instead of an object.

+4
source share
1 answer

I would use your idea encoded a little differently:

 var handleImpl = (function() { var implobj = { 23 : handleimpl1, 300 : handleimpl2, // ... defaultImpl: someDefaultFn } return function(i) { (implobj[i] || implobj.defaultImpl)(); }; }()); 
+7
source

All Articles