質問

the long hand if in javascript would look:

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帰属
所属していません StackOverflow
scroll top