user1966211 user1966211 - 1 year ago 38
Javascript Question

Javascript function accepts both arrays and strings as parameter

I have this code:

var showRegion = function(key) {
if (key in regionOptions) {
var entry = regionOptions[key];
var builder = entry.builder;
var layoutObj = entry.layoutObj;
var viewStarter = entry.viewStarter;

var view = new builder();'Controller.' + key + ' => CreateAccountLayoutController');

What I need is that the parameter should be able to accept an array or a string, and should work either way.

Sample function calls:

showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']);

Answer Source
var showRegion = function(key) {
    if (typeof key === 'string')
         key = [key];
    if (key in regionOptions) {

No need to make a code for each case, just convert key string into an array of one element and the code for arrays will do for both.