在javascript中,如何区分没有参数传递和未定义参数传递
in javascript, how to distinguish between no arg passed and undefined arg passed
在函数中,如何区分非参数和未定义的参数?
myFunc( 'first' );
var obj = { a: 123 };
myFunc( 'first', obj.b );
_or_
myFunc( 'first', undefined )
可以很容易地用arguments.length
指的是经过命名参数的参数,所以没有帮助arguments.length
解决-对不起,大脑屁!
function myFunc( a, b ) {
// Case A: if no second arg, provide one
// should be: if( arguments.length < 2 ) ...
if( b === undefined ) b = anotherFunc;
// Case B: if b is not resolved - passed but undefined, throw
else if( b === undefined ) throw( 'INTERNAL ERROR: undefined passed' );
// Case C: if b not a function, resolve by name
else if( typeof b != 'function' ) { ... }
...
}
myFunc
中大小写A和大小写B的正确方法是什么?
试试这样写:
function myFunc() {
var a, b;
if (arguments.length === 1) {
a = arguments[0];
console.log('no b passed');
}
else if (arguments.length > 1) {
a = arguments[0];
b = arguments[1];
if (b === undefined) {
console.log('undefined passed as parameter');
}
}
console.log(a, b);
}
myFunc(1);
myFunc(1, undefined);
我相信没有跨浏览器兼容的方法可以做到你想要的。此外,我认为当显式传递undefined
时(与根本不传递相比)改变其行为的函数令人困惑。也就是说,您可以通过稍微更改协议来实现总体目标。
让我们检查一下如何使用my_func:
my_func(1) // case A
my_func(1, undefined) // case B
my_func(1, {}.b) // case B
my_func(1, "blah") // case C
明白我的意思吗?只有当调用者传递单个参数时,情况A才会发生。
因此,如果你把my_func()
分成两个函数:my_funcA
,接受一个参数,my_funcBC
,接受两个参数,你将能够正确地实现你的逻辑。
这对函数的调用者造成的唯一变化是,如果调用者传递一个参数,他需要调用my_funcA()
。在所有其他情况下,应该调用my_funcBC()
。
function my_funcA(a) {
my_funcBC(a, anotherFunc);
}
function my_funcBC(a, b) {
if (b === undefined)
throw( 'INTERNAL ERROR: undefined passed' );
if (typeof b != 'function') { ... }
...
}
相关文章:
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 为什么我传递给函数的参数未定义
- 将对象作为参数传递后的未定义属性
- 为什么我的函数参数说是未定义的
- JavaScript onClick 参数表示未定义变量
- 对象属性来自方法参数时未定义
- 无法读取路由参数中未定义的属性“名称”
- require.js-未定义的模块作为参数传递以定义回调
- 为什么我得到错误参数是未定义的
- Reactjs路由器匹配回调参数总是未定义的
- 向函数传递未定义参数-检查变量是否存在
- 检查对象参数是否未定义
- 在jquery ajax中传递参数导致未定义
- 函数'的参数是未定义的,但我调用它传递所有必要的参数
- ColdFusion AJAX:元素在参数中未定义
- 在数组reduce中显式传递未定义的初始值
- 在javascript中传递函数作为参数,未定义错误
- 由于参数错误未定义,我无法创建jquery函数
- 请求参数排序未定义[在多部分/表单数据或一般中] - 该怎么办
- 通过参数设置未定义的参数