检查函数参数是否存在,并在JavaScript中键入

Check function parameters for existence and type in JavaScript

本文关键字:JavaScript 并在 函数 参数 是否 存在 检查      更新时间:2023-09-26

假设我定义了一个函数,例如:

var x = function (options, callback) { /* ... */ }

options需要具有属性foobar,其中foo的类型应为numberbar的类型为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);
}
相关文章: