简体   繁体   English

javascript简写(如果else回调)

[英]javascript shorthand if the else callback

the long hand if in javascript would look: 长手如果在javascript中将看起来:

function somefunction(param){

    if(typeof(param) != 'undefined'){
           var somevar = param;
         } else {

           alert('ERROR: missing parameter in somefunction. Check your form'); 
           return;

         }

}

AND MY SHORT HAND VERSION IS: 而我的简短版本是:

function somefunction(param){

    param = typeof(param) != 'undefined' ? param : function(){alert('ERROR: missing parameter in somefunction. Check your form'); return;}

}

BUT it does not work. 但是它不起作用。

How could I? 我怎么能?

Thank you 谢谢

You are only declaring the function. 您仅在声明该功能。 you have to execute it. 您必须执行它。 Add () next to the definition .. 在定义旁边添加()。

function somefunction(param){
    param = typeof(param) != 'undefined' ?
                param :
                function() {
                    alert('ERROR: missing parameter in somefunction. Check your form'); 
                    return false;
                }();
}

EDIT: The above is not functionally equivalent to the original as the function itself doesn't return anything and doesn't end the function execution. 编辑:上面的函数在功能上不等同于原始函数,因为函数本身不返回任何内容,也不终止函数的执行。

function somefunction(param) {
    if (typeof(param) == 'undefined') {
        alert('ERROR: missing parameter in somefunction. Check your form'); 
        return false;
    }

    // Use param
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM