I want to handle in an one function two ways of passing parameters. 1) It should be a standard way with passing single parameter 2) It should be a way with an array destruct to fetch all passed parameters in this array.
Something like this:
function a (z, c) {
console.log("z => ", z);
console.log("c => ", c);
}
let b = [1,2];
a(...b);
It works fine and prints both console log out. But I also want to have a possibility to pass an one parameter. Something like that:
function a (z, c) {
console.log("z => ", z);
console.log("c => ", c);
}
//now varibale b should contains a number, not an array.
//let b = [1,2];
// how can I detect that here is an one parameter
and I can't use the destructed parameter? How I can do this without changing a function call
let b = 1;
// throws an error
a(...b);
I can't assign the destruct operators result to some variable and test it's type via typeof etc. because in case of real destructing - it's impossible.
P.S. I know that the Destruct operator works only with arrays and it can't be applied to the Number. But it's just for an example.
I just wonder how I can pass or 1 parameter (like number) into a function or detect that that parameter is an array and I should fetch all array items and pass them into the function like in case with standard function call with multiple parameters
myFunc(1,2,3,4)
Maybe someone can help me? Thanks for any information.
UPDATE:
As like an ugly solution I can use simple if typechecking but I don't know how correct it will be.
function a (z, c) {
console.log("z => ", z);
console.log("c => ", c);
}
let b = 1;
if (~Object.prototype.toString.call(b).indexOf("Array")) {
a(...b);
} else {
a(b);
}
a(b)?a(b)and then check if b is an array within your function?Array.isArray(b)not thattoStringmagic