简体   繁体   中英

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();
            logger.info('Controller.' + key + ' => CreateAccountLayoutController');
            Controller.layout[layoutObj].show(view);
            view[viewStarter]();
        }
    };

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');
showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']);
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.

This post is old, but here is a pretty good tip:

function showRegions(keys) {
  keys = [].concat(keys)
  return keys
}

// short way
const showRegions = key => [].concat(keys)

showRegions(1) // [1]
showRegions([1, 2, 3]) // [1, 2, 3]

you could use typeof to check for the type of your argument and proceed accordingly, like

var showRegion = function(key) {
  if( typeof key === 'object') {
      //its an object
  }
  else {
     //not object
  }
}

You can use the fact that string.toString() always returns the same string and Array.toString() returns a comma-delimited string in combination with string.split(',') to accept three possible inputs: a string, an array, a comma-delimited string -- and reliably convert to an array (provided that you're not expecting commas to be part of the values themselves, and you don't mind numbers becoming strings).

In the simplest sense:

x.toString().split(',');

So that

'a' -> ['a']
['a','b'] -> ['a','b']
'a,b,c' -> ['a','b','c']
1 -> ['1']

Ideally, you may want to tolerate null, undefined, empty-string, empty-array (and still keep a convenient one-liner):

( (x || x === 0 ) && ( x.length || x === parseFloat(x) ) ? x.toString().split(',') : []);

So that also

null|undefined -> []
0 -> ['0']
[] -> []
'' -> []

You may want to interpret null/empty/undefined differently, but for consistency, this method converts those to an empty array, so that downstream code does not have to check beyond array-having-elements (or if iterating, no check necessary.)

This may not be terribly performant, if that's a constraint for you.

In your usage:

var showRegion = function(key) {
    key = ( (key || key === 0 ) && ( key.length || key === parseFloat(key) ) ? key.toString().split(',') : []);

    /* do work assuming key is an array of strings, or an empty array */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM