开发者

Way to check a bunch of parameters if they are set or not in JavaScript

开发者 https://www.devze.com 2023-01-28 17:15 出处:网络
So, this happens to me quite frequently, but here\'s my latest one: var generic_error = function(title,msg){

So, this happens to me quite frequently, but here's my latest one:

  var generic_error = function(title,msg){
        if(!title){ title= 'Oops!'; }
        if(!msg) { msg = 'Something must have gone wrong, but no worries we\'re working on it!'; }
        $.fancybox(
        {
            content:'\
                <div class="error_alert">\
                    <h2>'+title+'</h2>\
                    <p>'+msg+'\
                </div>'
        });
    }

Is there a cleaner way to check all params like title and msg above and OR set them as optional OR define defaults in the function like how PHP does it for example? Sometimes i could have 10 options and if(!var){var='defaults'} x 10 is 开发者_StackOverflow中文版icky...


Slightly shorter but equivalent to what you're doing now is to use "||" AKA "or" AKA "the default operator".

title = title || 'Oops!';
 msg = msg || 'Something must have gone wrong, but no worries we\'re working on it!';


I doubt you'll find anything considerably shorter and simpler than if(!title)title='DefaultTitle' for function arguments.

However, I'd even use the longer form to make it more explicit: if (title===null) title='DefaultTitle'.

Here is a related question with an answer, but I think it would just makes your code more complicated. How can I access local scope dynamically in javascript?


You could use ternary notation as recommended by this article but in a simpler form:

var n = null;
!title ? title = 'Oops' : n;

You've also got the arguments[] array which holds the arguments and could be used in a loop, something like this:

function test(one,two,three) {
  i=0;
  while(typeof(arguments[i]) != 'undefined') {
    alert(arguments[i++]);
  }
}

test(40,27,399);


switch (arguments.length) {
  case 0: title = 'Oops';
  case 1: message = 'Something must have gone wrong...';
}


Here's another approach. The argsOK function is a little complex, but calling it is easy.

//-----------------------------------------------------
/*
PURPOSE Ensures a function received all required arguments, no extra 
        arguments & (if so specified) no arguments are empty.
RETURNS True if the arguments validate, else false.
*/
function argsOk(
    functionCallee  ,   // Caller's callee object
    allArgsRequired ,   // True = All arguments are required
    emptyArgsAllowed    // True = Empty arguments are allowed
){
    var ok = true;
    for (var i = 0; i < 1; ++i) {
        var functionName = functionCallee.toString().split(' ')[1].split('(')[0];
        var args = functionCallee.arguments;
        var expectedArgCount = functionCallee.length;
        var actualArgCount  = args.length;
        if ((allArgsRequired && actualArgCount < expectedArgCount) ||
            (actualArgCount > expectedArgCount)) {
            error("Function " + functionName + " expected " + expectedArgCount + " arguments, but received " + actualArgCount + ".");
            ok = false;
            break;
        }
        if (emptyArgsAllowed) {
            break;
        }
        for (var j = 0; j < args.length; ++j) {
            if (args[j] != null && args[j].length == 0) {
                error("Function " + functionName + "() received an empty argument.");
                ok = false;
                break;
            }
        }
    }
    return ok;
}

Example of calling it (a one-liner, as you can see):

//------------------------------------------------
function image(item, name, better)
// PURPOSE Write a request for picture or photo
// ENTRY        Init() has been called
{
    if (!showingShortVersion()) {
        var betterString = '';
        if (better != null && better == true)
            betterString = 'better ';
        if (argsOk(arguments.callee, true, false))
            write('<p class="request maintain">If you have ac&shy;cess to a ' + betterString + item + ' of ' + name + ' that we could put on&shy;line, please <a href="misc/pics.htm" onmouseover="return stat(\'Learn how to send us images\')" onmouseout="return erase()">click here</a>.</p>');
    }
}


In general, especially in Javascript, clean != short.

Do not use if(!title){ title= 'Oops!'; } as a general solution, because e.g. 0 and empty string are falsy, too. Arguments that are not set, are undefined, so I prefer using

if (title === undefined) {
    title= 'Oops!'; 
}

It may be more wordy to do so, but It will prevent unwanted side effects, and in my experience, Javascript generates a lot of unwanted side effects, if you try to use shortcuts.

0

精彩评论

暂无评论...
验证码 换一张
取 消