在Javascript中检查函数参数的类型 [英] Checking the types of function arguments in Javascript
本文介绍了在Javascript中检查函数参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Javascript中,有没有办法检查函数参数的类型?我想写一个名为 checkTypes
的函数执行以下操作:
In Javascript, is there any way to check the types of a function's arguments? I want to write a function called checkTypes
that does the following:
function checkTypes(typeArr){
//if the types do not match typeArr, throw an error
}
function exampleUsage(arr1, arr2, num1){
checkTypes("object", "object", "number");
//throw an error if the types do not match the corresponding elements
}
推荐答案
你可以使用改编自这篇文章的 typeOf
函数修复JavaScript typeof运算符结合此函数:
You can use the the typeOf
function adapted from this post Fixing the JavaScript typeof operator combined with this function:
function typeOf( obj ) {
return ({}).toString.call( obj ).match(/\s(\w+)/)[1].toLowerCase();
}
function checkTypes( args, types ) {
args = [].slice.call( args );
for ( var i = 0; i < types.length; ++i ) {
if ( typeOf( args[i] ) != types[i] ) {
throw new TypeError( 'param '+ i +' must be of type '+ types[i] );
}
}
}
function foo( a,b,c ) {
checkTypes( arguments, ['string', 'number', 'array'] );
return 'foo';
}
console.log( foo( 'a', 1, [2] ) ); //=> foo
console.log( foo( 1, 1, [2] ) );
//^ Uncaught TypeError: param 0 must be of type string
这篇关于在Javascript中检查函数参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文