我已经看到了两种方法,用于确定参数是否已传递给JavaScript函数。我想知道是一种方法比另一种好,还是一种方法不好用?

 function Test(argument1, argument2) {
      if (Test.arguments.length == 1) argument2 = 'blah';

      alert(argument2);
 }

 Test('test');

Or

 function Test(argument1, argument2) {
      argument2 = argument2 || 'blah';

      alert(argument2);
 }

 Test('test');

据我所知,它们的结果是一样的,但我以前在生产中只使用过第一个。

Tom提到的另一个选择:

function Test(argument1, argument2) {
    if(argument2 === null) {
        argument2 = 'blah';
    }

    alert(argument2);
}

根据Juan的评论,Tom的建议最好改为:

function Test(argument1, argument2) {
    if(argument2 === undefined) {
        argument2 = 'blah';
    }

    alert(argument2);
}

当前回答

为什么不用!!运营商吗?这个运算符,放在变量之前,把它变成一个布尔值(如果我理解得很好),所以!!未定义和!!Null(甚至!!)NaN,这很有趣)将返回false。

这里有一个例子:

function foo(bar){
    console.log(!!bar);
}

foo("hey") //=> will log true

foo() //=> will log false

其他回答

如果您正在使用jQuery,一个不错的选择(特别是对于复杂的情况)是使用jQuery的extend方法。

function foo(options) {

    default_options = {
        timeout : 1000,
        callback : function(){},
        some_number : 50,
        some_text : "hello world"
    };

    options = $.extend({}, default_options, options);
}

如果你像这样调用函数:

foo({timeout : 500});

选项变量将是:

{
    timeout : 500,
    callback : function(){},
    some_number : 50,
    some_text : "hello world"
};

为什么不用!!运营商吗?这个运算符,放在变量之前,把它变成一个布尔值(如果我理解得很好),所以!!未定义和!!Null(甚至!!)NaN,这很有趣)将返回false。

这里有一个例子:

function foo(bar){
    console.log(!!bar);
}

foo("hey") //=> will log true

foo() //=> will log false
function example(arg) {
  var argumentID = '0'; //1,2,3,4...whatever
  if (argumentID in arguments === false) {
    console.log(`the argument with id ${argumentID} was not passed to the function`);
  }
}

因为数组继承自Object.prototype。想让世界更美好。

有时你想要undefined作为一个可能的参数,但你仍然有可能不传递参数的情况。在这种情况下,你可以使用参数。长度来检查传递了多少个参数。


// Throw error if the field is not matching our expectations
function testField(label, fieldValue, expectedValue) {
    console.log(arguments) // Gives: [Arguments] { '0': 'id', '1': 1, '2': undefined }
    if(arguments.length === 2) {
        if(!fieldValue) {
            throw new Error(`Field "${label}" must have a value`)
        }
    }

    else if(expectedValue === undefined) {
        if(fieldValue !== undefined) {
            throw Error(`Field "${label}" must NOT have a value`)
        }
    }

    // We stringify so our check works for objects as well
    else {
        if(JSON.stringify(fieldValue) !== JSON.stringify(expectedValue)) {
            throw Error(`Field "${label}" must equal ${expectedValue} but was ${fieldValue}`)
        }
    }
}

testField('id', 12) ->传递,我们不希望id为空

testField('id', undefined, undefined) ->通过,我们希望id为undefined

testField('id', 12, undefined) ->错误,我们希望id是undefined

通过调用带有可选属性的Object来调用函数,可以方便地检测参数:

function foo(options) {
    var config = { // defaults
        list: 'string value',
        of: [a, b, c],
        optional: {x: y},
        objects: function(param){
           // do stuff here
        }
    }; 
    if(options !== undefined){
        for (i in config) {
            if (config.hasOwnProperty(i)){
                if (options[i] !== undefined) { config[i] = options[i]; }
            }
        }
    }
}