gpt4 book ai didi

javascript - 检查js函数中未定义的参数

转载 作者:行者123 更新时间:2023-12-01 02:03:52 25 4
gpt4 key购买 nike

当非函数数据类型为时,我需要一些条件来捕获并抛出错误作为第二个参数传递。

包括未定义的传递?

function test(fn) {
console.log(fn)
// should throw an error if a non-function data type is
//passed as the second argument (includes undefined being passed)
if (fn && typeof fn !== 'function') throw Error();
return fn;
}


function demo() {}

test(); //undefined OK!

test(undefined); // SHOULD THROW ERROR ALSO

// throws error since argument is defined and not a function
test('sdfasfs');

最佳答案

区分隐式和显式传递 undefined 的唯一方法是查看传递了多少个参数:

function test(fn) {
console.log(fn)
// should throw an error if a non-function data type is
//passed as the second argument (includes undefined being passed)
if (arguments.length > 0 && typeof fn !== 'function') throw Error();
return fn;
}


function demo() {}

test(); //undefined OK!

test(undefined); // SHOULD THROW ERROR ALSO

// throws error since argument is defined and not a function
test('sdfasfs');

关于javascript - 检查js函数中未定义的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50285226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com