检查函数参数是否存在,并在JavaScript中键入
Check function parameters for existence and type in JavaScript
假设我定义了一个函数,例如:
var x = function (options, callback) { /* ... */ }
options
需要具有属性foo
和bar
,其中foo
的类型应为number
,bar
的类型为string
。
所以,基本上,我可以使用以下代码来检查:
var x = function (options, callback) {
if (!options) { throw new Error('options is missing.'); }
if (!options.foo) { throw new Error('foo is missing.'); }
if (!options.bar) { throw new Error('bar is missing.'); }
if (!callback) { throw new Error('callback is missing.'); }
// ...
}
但这只是检查是否存在,而不是检查正确的类型。当然,我可以添加更多的检查,但这很快就会变得冗长,可读性也不太好。一旦我们开始谈论可选参数,它就会变得一团糟,参数会发生变化等等…
处理这个问题的最佳方法是什么(假设你想检查一下)?
更新
为了澄清我的问题:我知道有typeof
运算符,我也知道如何处理可选参数。但我必须手动进行所有这些检查,这肯定不是我们能想到的最好的。
我问题的目的是:是否有现成的函数/库/任何你能告诉你的东西,你期望五个特定类型的参数,一些是强制性的,一些是可选的,函数/库为你做检查和映射,这样所有这些都可以归结为一行?
基本上,像这样的东西
var x = function (options, callback) {
verifyArgs({
options: {
foo: { type: 'number', mandatory: true },
bar: { type: 'string', mandatory: true }
},
callback: { type: 'function', mandatory: false }
});
// ...
};
javascript具有typeof
console.log( typeof '123' ); // string
console.log( typeof 123 ); // number
console.log( typeof undefinedVar); // undefined
var x = function (options, callback) {
if (typeof options =='undefined' { throw new Error('options is missing.'); }
if (typeof options.foo !='number') { throw new Error('foo is missing.'); }
if (typeof options.bar !='string') { throw new Error('bar is missing.'); }
if (typeof callback!= 'function') { throw new Error('callback is missing.'); }
// ...
}
您可以这样做:
var x = function (options, callback) {
var options = options || {};
if (typeof options.foo != 'number') {
throw new Error('foo need to be a number.');
}
if (typeof options.bar != 'string') {
throw new Error('bar need to be a string.');
}
// ...
}
使用类型
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
查看以下检查类型、字符串或整数的示例:
if(typeof(somevar) === 'string') alert('string');
if(typeof(somevar)==="number" && Math.round(somevar) == somevar) alert('is int');
if (myObj.hasOwnProperty(myProp)) { //to check whether mentioned property exist
if (typeof myObj[myProp] == "string") { //or integer
// your code to be executed!!!
} else {
//ERROR!!!
}
}
虽然这并不是javascript类型模型背后的想法,但我通常使用for
循环来迭代待检查对象的数据成员:
/* (.startsWith has to be implementes somehow) */
for (key in my_object_with_data) {
if (!key.startsWith(typeof my_object_with_data[key]+"_") {
/* The member "key" has wrong type. */
}
}
例如,对象的成员必须命名为number_a
,以检查其类型是否为数字。
可以通过一些通用检查方法进行额外的验证,这些方法可以根据typeof
值应用于for循环内部。
好吧,我找到了一个自己想做什么的库,它叫ArgueJS:
function range(){
arguments = __({start: [Number, 0], stop: Number, step: [Number, 1]})
for(var i = arguments.start; i < arguments.stop; i += arguments.step)
console.log(i);
}
相关文章:
- 使用javascript检查多个输入值,并在1次检查中标记多个输入框
- 如何覆盖锚点元素's href目标,并在我点击转到目标javascript时删除其他错误
- 通过ajax将坐标传递到php服务器端,并在处理后检索到javascript
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 从数组中删除重复条目,并在javascript中按顺序排列
- 如何使用Javascript在给定的句子中找到大写单词并在其前面添加一个字符
- 如何使用javascript localStorage保存用户选择并在不同的html页面中显示
- 如何将(a*b)两个输入文本值相乘,并在javascript中随文本变化动态显示
- 如何获取javascript输入并在html中调用它
- javascript从选中的复选框中检索输入值,并在同一网页中显示多个html文件
- 使用javascript读取本地XML文件并在html页面中显示
- 如何在打印前等待javascript文件加载twitter,并在打印后关闭选项卡
- 在Javascript中解析json并在html上创建表
- javascript window.open(),并在新窗口中搜索DOM
- Javascript性能-在dom上迭代并添加侦听器
- 如何使用Javascript获取当前页面URL,并在<a href="[the_URL]”>
- 如何将多维传递给javascript并在多维中再次存储
- 调用javascript并在右侧框架中显示结果
- 如果路径中有一个querystring, Firefox是否缓存javascript并在没有请求的情况下使用它?
- 如何使用JavaScript并在Kendo UI模板中打印结果