Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function accepts both arrays and strings as parameter

Tags:

javascript

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']);
like image 765
user1966211 Avatar asked May 20 '13 03:05

user1966211


People also ask

Can array be parameter in a function JavaScript?

As such, Javascript provides us with two ways to use arrays as function parameters in Javascript - apply() and the spread operator.

Which function accepts two arguments in JavaScript?

Let's start by creating a function called add that can accept 2 arguments and that returns their sum. We can use Node. js to run the code node add_2_numbers.

Can JavaScript function accept parameters?

A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.

Can a parameter be a string in JavaScript?

Can a parameter be a string in JavaScript? If a function takes a DOM element as a parameter, it can be a string, or a jQuery object, for example.


2 Answers

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]
like image 179
Cohars Avatar answered Oct 18 '22 17:10

Cohars


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.

like image 24
Havenard Avatar answered Oct 18 '22 15:10

Havenard