Quiero crear una función como:
var func = function(arg1, arg2) { callAnotherFunc(arg1, arg2); } como puede ver, cuando alguien necesita llamar a func , necesita pasar 2 argumentos. a veces, arg2 puede ser nulo.
A veces, arg2 será nulo. ¿Hay algún atajo que me permita hacer esto?
var func = function(arg1, arg2) { callAnotherFunc(arg1, arg2 || nothing); } Entonces, si arg2 es nulo, no debería pasar ningún otro argumento para callAnotherFunc a otra función. Estoy buscando algún atajo y no if/else
No entiendo por qué querrías esto, tal vez tus intenciones están más allá de mi comprensión. Solo puede usar parámetros predeterminados
var func = function(arg1, arg2 = null) { callAnotherFunc(arg1, arg2); } var callAnotherFunc = function(arg1, arg2 = null){ // console.log(arg1); // console.log(arg2); }Puedes intentar algo como esto
Cómo usar los argumentos y parámetros de ES6
var func = (...args) => { callAnotherFunc(...args); } var callAnotherFunc = (...args) =>{ console.log(...args) } func(1); func(1,2); func(1,2,3);Puede reenviar todos los arguments que no son null usando call .
var callAnotherFunc = function(){ console.log(arguments) }; var func = function(arg1, arg2){ //So if arg2 is null, it shouldn't pass another argument to callAnotherFunc at all. callAnotherFunc.call( null, Array.from(arguments).filter(function(item, index){ return index == 0 || item !== null }) ) }; func(1, 2); func(1, null); //REM: Does not pass second argument func(null, null); //REM: Does not pass second argument