我现在已经看到了两种确定参数是否已传递给JavaScript函数的方法.我想知道一种方法是否优于另一种方法,或者一种方法是否使用不好?
function Test(argument1, argument2) {
if (Test.arguments.length == 1) argument2 = 'blah';
alert(argument2);
}
Test('test');
Run Code Online (Sandbox Code Playgroud)
要么
function Test(argument1, argument2) {
argument2 = argument2 || 'blah';
alert(argument2);
}
Test('test');
Run Code Online (Sandbox Code Playgroud)
据我所知,它们都产生了相同的结果,但我在生产之前只使用过第一个.
汤姆提到的另一个选择:
function Test(argument1, argument2) {
if(argument2 === null) {
argument2 = 'blah';
}
alert(argument2);
}
Run Code Online (Sandbox Code Playgroud)
根据胡安的评论,将汤姆的建议改为:
function Test(argument1, argument2) {
if(argument2 === undefined) {
argument2 = 'blah';
}
alert(argument2);
}
Run Code Online (Sandbox Code Playgroud) 我目前正在创建一个javascript函数库.主要是供我自己使用,但你永远无法确定是否有其他人最终在他们的项目中使用它,我至少创造它就好像这可能发生.
大多数方法仅在传递的变量具有正确的数据类型时才有效.现在我的问题是:提醒用户该变量的类型不正确的最佳方法是什么?应该抛出这样的错误吗?
function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
if(typeof(thisShouldBeAString) === 'string') {
throw('foo(var), var should be of type string');
}
#yadayada
}
Run Code Online (Sandbox Code Playgroud)
我知道javascript会进行内部类型转换,但这会产生非常奇怪的结果(即'234'+ 5 ='2345'但是'234'*1 = 234)这可能会让我的方法做得非常奇怪.
编辑
为了使事情更清楚:我不希望进行类型转换,传递的变量应该是正确的类型.告诉我的库用户传递的变量类型不正确的最佳方法是什么?