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']);
As such, Javascript provides us with two ways to use arrays as function parameters in Javascript - apply() and the spread operator.
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.
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? If a function takes a DOM element as a parameter, it can be a string, or a jQuery object, for example.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With