9

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
}
4

7 に答える 7

14

typeOfこの投稿から適応された関数を使用できますこの関数と組み合わせた JavaScript typeof 演算子の修正:

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
于 2012-12-18T04:33:30.720 に答える
10

この場合は使用しないでくださいtypeof。いくつかの理由で問題があります:

typeof null                 // 'object'
typeof []                   // 'object'
typeof 'foo'                // 'string'
typeof new String('foo')    // 'object'
'foo' == new String('foo')  // true

代わりに、次を使用します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]'

デコレータはあなたの要件を満たします:

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

使用例:

exampleUsage([], [], 0);
// arr1: []
// arr2: []
// num1: 0

exampleUsage([], [], 'foo');
// TypeError: expected number; received string
于 2012-12-18T06:27:21.163 に答える
3

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]);
        }
    }
}

実際のデモ: http://jsfiddle.net/jfriend00/ywyLe/


使用例:

function exampleUsage(arr1, arr2, num1){
    //throw an error if the types do not match the corresponding elements
    checkTypes(arguments, ["array", "array", "number"]);
}
于 2012-12-18T04:44:07.857 に答える
0

typeof演算子を探しています。

于 2012-12-18T04:24:50.413 に答える
0

ほとんどの場合、 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 */

しかし、jQueryはこの関数で識別できます jQuery.type( obj ) http://api.jquery.com/jQuery.type/

于 2012-12-18T04:47:18.950 に答える
-4

JavaScript は型には適していません。また、呼び出し元の関数から親の関数引数に魔法のようにアクセスすることはできません。

大きな頭痛の種になりたくない場合は、単純なライブラリを使用して型をチェックしてください。

たとえば、underscore.jsを使用すると、次のように記述できます。

function exampleUsage(arr1, arr2, num1) {
  if(!_.isArray(arr1) || !_.isArray(arr2) || !_.isNumber(num1) {
    throw "Wrong types"
  }
  // do other stuff
}

あなたはおそらく動的言語に慣れていないため、型を恐れているでしょう。見た目ほど悪くはありませんが、JavaScrip は悪いものです (他の多くの理由により)。

于 2012-12-18T04:31:51.607 に答える