简体   繁体   English

Javascript函数接受数组和字符串作为参数

[英]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 您可以使用typeof来检查您的参数的类型并相应地继续,例如

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). 您可以使用string.toString()始终返回相同字符串的事实,并且Array.toString()返回逗号分隔的字符串以及string.split(',')以接受三个可能的输入:字符串,数组,逗号分隔的字符串 - 并可靠地转换为数组(前提是您不希望逗号成为值本身的一部分,并且您不介意数字成为字符串)。

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): 理想情况下,您可能希望容忍null,undefined,empty-string,empty-array(并且仍然保持方便的单行):

( (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.) 您可能希望以不同方式解释null / empty / undefined,但为了保持一致性,此方法将这些转换为空数组,以便下游代码不必检查array-having-elements(或者如果迭代,则无需检查)。

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 */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript-数组函数:创建一个接受单个参数作为参数的 function:字符串数组 - Javascript- Array functions :Create a function that accepts a single parameter as an argument: an array of strings Javascript-接受参数并返回包含“ x”的字符串的函数 - Javascript - A function that accepts parameter and return a string which contains “x” 在接受参数的函数内部循环 - Loop inside the function that accepts the parameter Java和Javascript绑定函数,将数组作为参数 - Java and Javascript bind function with arrays as parameter 使用JavaScript中的一个函数从数组和对象中获取键 - Get keys from both arrays and objects using one function in JavaScript 创建一个接受另一个函数作为参数的函数 - Creating a function that accepts another function as a parameter JavaScript 的 JSON.Parse() 函数是否对它接受的参数有最大字符串长度限制? - Does JavaScript's JSON.Parse() function have a max string length limit for the parameter it accepts? Javascript:如何创建一个函数 1. 接受一个全局变量作为参数 2. 改变该全局变量的值? - Javascript: How can I create a function that 1. accepts a global variable as a parameter 2. alters the value of that global variable? Javascript嵌套数组与字符串 - Javascript nested arrays with strings Javascript结合了数组或字符串 - Javascript combine arrays or strings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM