检查存在的函数参数并在JavaScript中键入

时间:2013-08-26 07:55:05

标签: javascript

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

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

options需要包含属性foobar,其中foo的类型为numberbar的类型为string 1}}。

所以,基本上,我可以使用以下代码检查:

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 }
  });
  // ...
};

7 个答案:

答案 0 :(得分:1)

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.'); }
  // ...
}

答案 1 :(得分:1)

你可以这样做:

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.');
    }
    // ...
}

答案 2 :(得分:0)

使用typeof

// 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!

...

答案 3 :(得分:0)

if (myObj.hasOwnProperty(myProp)) { //to check whether mentioned property exist
    if (typeof myObj[myProp] == "string") { //or integer
        // your code to be executed!!!
    } else {
        //ERROR!!!
    }
}

答案 4 :(得分:0)

请参阅以下示例以检查类型,字符串或整数:

if(typeof(somevar) === 'string') alert('string');
if(typeof(somevar)==="number" && Math.round(somevar) == somevar) alert('is int');

答案 5 :(得分:0)

虽然这不是完全 javascript类型模型背后的想法,但我通常使用for - 循环来迭代我的to-check-object的数据成员:

/* (.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循环中应用。

答案 6 :(得分:0)

好的,我找到了一个自己做我想做的图书馆,名为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);
}
相关问题