在 Javascript 中检查函数参数的类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13926213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking the types of function arguments in Javascript
提问by Anderson Green
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:
在 Javascript 中,有没有办法检查函数参数的类型?我想编写一个名为的函数checkTypes
,它执行以下操作:
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
}
回答by elclanrs
You can use the the typeOf
function adapted from this post Fixing the JavaScript typeof operatorcombined with this function:
您可以使用typeOf
改编自这篇文章的函数Fixing the JavaScript typeof operator与此函数结合使用:
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
回答by davidchambers
Do not use typeof
in this case. It's problematic for several reasons:
typeof
在这种情况下不要使用。由于以下几个原因,它有问题:
typeof null // 'object'
typeof [] // 'object'
typeof 'foo' // 'string'
typeof new String('foo') // 'object'
'foo' == new String('foo') // true
Instead, use Object::toString
:
相反,使用Object::toString
:
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call('foo') // '[object String]'
Object.prototype.toString.call(new String('foo')) // '[object String]'
A decorator would meet your requirements:
装饰器将满足您的要求:
var getType = function(value) {
return Object.prototype.toString.call(value)
.replace(/^\[object |\]$/g, '').toLowerCase();
};
var checkTypes = function(types, fn) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
for (var idx = 0; idx < types.length; idx += 1) {
var expected = types[idx];
var received = getType(args[idx]);
if (received != expected) {
throw new TypeError('expected ' + expected + '; received ' + received);
}
}
fn.apply(null, args);
};
};
var exampleUsage = checkTypes(['array', 'array', 'number'], function(arr1, arr2, num1) {
console.log('arr1:', arr1);
console.log('arr2:', arr2);
console.log('num1:', num1);
});
Usage examples:
用法示例:
exampleUsage([], [], 0);
// arr1: []
// arr2: []
// num1: 0
exampleUsage([], [], 'foo');
// TypeError: expected number; received string
回答by jfriend00
You can use a modified version of typeof
and the arguments
pseudo-array to get each argument type and compare it to your desired set of types:
您可以使用typeof
和arguments
伪数组的修改版本来获取每个参数类型并将其与所需的类型集进行比较:
// from Doug Crockford http://javascript.crockford.com/remedial.html
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (Object.prototype.toString.call(value) == '[object Array]') {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
function checkTypes(argList, typeList) {
for (var i = 0; i < typeList.length; i++) {
if (typeOf(argList[i]) !== typeList[i]) {
throw 'wrong type: expecting ' + typeList[i] + ", found " + typeOf(argList[i]);
}
}
}
Working demo: http://jsfiddle.net/jfriend00/ywyLe/
工作演示:http: //jsfiddle.net/jfriend00/ywyLe/
Example Usage:
示例用法:
function exampleUsage(arr1, arr2, num1){
//throw an error if the types do not match the corresponding elements
checkTypes(arguments, ["array", "array", "number"]);
}
回答by Kashif Naseem
The typeof function return object for most of the thing,
大多数事物的 typeof 函数返回对象,
alert(typeof("this is string")); /* string */
alert(typeof(1234)); /* number */
alert(typeof([])); /* object */
alert(typeof({})); /* object */
alert(typeof(new Date)); /* object */
alert(typeof(function(){})); /* function */
but jQuery can identify by this function jQuery.type( obj ) http://api.jquery.com/jQuery.type/
但是 jQuery 可以通过这个函数来识别 jQuery.type( obj ) http://api.jquery.com/jQuery.type/
回答by Pawe?
If anyone is looking for require-like environment solution, I can recommend typeof-argumentspackage.
如果有人正在寻找类似 require 的环境解决方案,我可以推荐typeof-arguments包。
const checkTypes = require('typeof-arguments');
function exampleUsage(arr1, arr2, num1){
checkTypes(arguments,["object", "object", "number"]);
//throw an error if the types do not match the corresponding elements
}
回答by tothemario
JavaScript is bad for types. Also, you can not magically access the parent's function arguments from a calling function.
JavaScript 对类型不利。此外,您不能从调用函数神奇地访问父函数的参数。
If you don't want to have a big headache, use some simple library to check types.
如果您不想头疼,可以使用一些简单的库来检查类型。
For example, using underscore.jsyou could write something like this:
例如,使用underscore.js你可以这样写:
function exampleUsage(arr1, arr2, num1) {
if(!_.isArray(arr1) || !_.isArray(arr2) || !_.isNumber(num1) {
throw "Wrong types"
}
// do other stuff
}
You are probably afraid of types because you are probably new to dynamic languages. You will see that is not as bad as it looks like, but JavaScrip IS BAD (for a lot other reasons)
您可能害怕类型,因为您可能不熟悉动态语言。你会发现它并不像看起来那么糟糕,但 JavaScrip 是糟糕的(出于很多其他原因)