8

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']);
4

4 回答 4

17

这篇文章很旧,但这里有一个很好的提示:

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]
于 2016-07-10T01:24:29.423 回答
9
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.

于 2013-05-20T03:36:05.700 回答
0

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
  }
}
于 2013-05-20T03:37:31.983 回答
-1

您可以使用 string.toString() 始终返回相同的字符串和 Array.toString() 返回逗号分隔的字符串与 string.split(',') 结合的事实来接受三个可能的输入:字符串、数组,一个逗号分隔的字符串——并且可靠地转换为一个数组(前提是您不希望逗号成为值本身的一部分,并且您不介意数字变成字符串)。

在最简单的意义上:

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

以便

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

理想情况下,您可能希望容忍 null、未定义、空字符串、空数组(并且仍然保持方便的单行):

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

所以那也

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

您可能希望以不同的方式解释 null/empty/undefined,但为了保持一致性,此方法将它们转换为空数组,以便下游代码不必检查超出数组的元素(或者如果迭代,则无需检查。)

如果这对您来说是一个限制,那么这可能不是非常高效。

在您的使用中:

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 */
}
于 2016-12-15T19:25:02.183 回答