문제

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