Recherche d'un type de variable dans JavaScript


146

En Java, vous pouvez utiliser instanceOfou getClass()sur une variable pour connaître son type.

Comment connaître le type d'une variable en JavaScript qui n'est pas fortement typé?

Par exemple, comment savoir si le barest a Booleanou a Number, ou a String?

function foo(bar) {
    // what do I do here?
}

Réponses:


242

Utilisez typeof:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

Vous pouvez donc faire:

if(typeof bar === 'number') {
   //whatever
}

Attention cependant si vous définissez ces primitives avec leurs wrappers d'objet (ce que vous ne devriez jamais faire, utilisez des littéraux dans la mesure du possible):

> typeof new Boolean(false)
"object"
> typeof new String("foo")
"object"
> typeof new Number(42)
"object"

Le type d'un tableau est toujours object. Ici, vous avez vraiment besoin de l' instanceofopérateur.

Mettre à jour:

Une autre manière intéressante consiste à examiner la sortie de Object.prototype.toString:

> Object.prototype.toString.call([1,2,3])
"[object Array]"
> Object.prototype.toString.call("foo bar")
"[object String]"
> Object.prototype.toString.call(45)
"[object Number]"
> Object.prototype.toString.call(false)
"[object Boolean]"
> Object.prototype.toString.call(new String("foo bar"))
"[object String]"
> Object.prototype.toString.call(null)
"[object Null]"
> Object.prototype.toString.call(/123/)
"[object RegExp]"
> Object.prototype.toString.call(undefined)
"[object Undefined]"

Avec cela, vous n'auriez pas à faire la distinction entre les valeurs primitives et les objets.


Quel serait l' inconvénient d'utiliser proto .constructor.name une fonction siple serait: function getVariableType (object) {return (object .__ proto__.constructor.name); }
Stu

mise à jour de la définition de fonction mentionnée ci-dessus: function getVariableType (object) {return (object === undefined? "Undefined": object.__proto__.constructor.name);
Stu

29

typeof n'est bon que pour renvoyer les types "primitifs" tels que nombre, booléen, objet, chaîne et symboles. Vous pouvez également utiliser instanceofpour tester si un objet est d'un type spécifique.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

23

Utilisation type:

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

// Strings
typeof ""                === 'string';
typeof "bla"             === 'string';
typeof (typeof 1)        === 'string'; // typeof always return a string
typeof String("abc")     === 'string'; // but never use this form!

// Booleans
typeof true              === 'boolean';
typeof false             === 'boolean';
typeof Boolean(true)     === 'boolean'; // but never use this form!

// Undefined
typeof undefined         === 'undefined';
typeof blabla            === 'undefined'; // an undefined variable

// Objects
typeof {a:1}             === 'object';
typeof [1, 2, 4]         === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date()        === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1)     === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

// Functions
typeof function(){}      === 'function';
typeof Math.sin          === 'function';

Il n'y a aucun problème avec l'utilisation Number(1), Boolean(true)...Les seuls problèmes sont lorsque vous utilisez newet qu'un objet encadré est créé, les utiliser comme fonctions peut être en fait utile pour convertir d'autres types. Boolean(0) === false, Number(true) === 1
Juan Mendes

et quoi null? typeof nullest 'objet'
Dheeraj

15

En Javascript, vous pouvez le faire en utilisant la fonction typeof

function foo(bar){
  alert(typeof(bar));
}

3
Comme je l'ai mentionné dans ma réponse, typof ne retournera que le nombre, le booléen, l'objet, la chaîne. Pas utile pour déterminer d'autres types, comme Array, RegExp ou des types personnalisés.
Juan Mendes

7

Pour être un peu plus précis à ECMAScript-5.1 que les autres réponses (certains pourraient dire pédant):

En JavaScript, les variables (et les propriétés) n'ont pas de types: les valeurs en ont. De plus, il n'y a que 6 types de valeurs: non défini, nul, booléen, chaîne, nombre et objet. (Techniquement, il existe également 7 "types de spécification", mais vous ne pouvez pas stocker les valeurs de ces types en tant que propriétés d'objets ou valeurs de variables - elles ne sont utilisées que dans la spécification elle-même, pour définir le fonctionnement du langage. Les valeurs que vous pouvez manipuler explicitement ne sont que des 6 types que j'ai énumérés.)

La spécification utilise la notation "Type (x)" lorsqu'elle veut parler du "type de x". Ce n'est qu'une notation utilisée dans la spécification: ce n'est pas une caractéristique du langage.

Comme d'autres réponses l'indiquent clairement, dans la pratique, vous voudrez peut-être en savoir plus que le type d'une valeur - en particulier lorsque le type est Object. Quoi qu'il en soit, et par souci d'exhaustivité, voici une implémentation JavaScript simple de Type (x) telle qu'elle est utilisée dans la spécification:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

Il y a aussi des symboles
Juan Mendes

Pas dans ECMAScript 5.1, il n'y en a pas.
Wes

6

Je trouve frustrant que ce typeofsoit si limité. Voici une version améliorée:

var realtypeof = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            if (obj instanceof Date)
                return '[object Date]';
            if (obj instanceof RegExp)
                return '[object regexp]';
            if (obj instanceof String)
                return '[object String]';
            if (obj instanceof Number)
                return '[object Number]';

            return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};

échantillon test:

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 

3

Pour les types JS intégrés, vous pouvez utiliser:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Ici, nous utilisons la méthode 'toString' de la classe 'Object' qui fonctionne différemment de la même méthode d'un autre type.

Exemples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

Si vous avez besoin d'un nom de classe, vous pouvez utiliser:

instance.constructor.name

Exemples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

Mais cette fonctionnalité a été ajoutée dans ES2015 .


1

Voici la solution complète.

Vous pouvez également l'utiliser comme classe Helper dans vos projets.

"use strict";
/**
 * @description Util file
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

window.Sys = {};

Sys = {
  isEmptyObject: function(val) {
    return this.isObject(val) && Object.keys(val).length;
  },
  /** This Returns Object Type */
  getType: function(val) {
    return Object.prototype.toString.call(val);
  },
  /** This Checks and Return if Object is Defined */
  isDefined: function(val) {
    return val !== void 0 || typeof val !== 'undefined';
  },
  /** Run a Map on an Array **/
  map: function(arr, fn) {
    var res = [],
      i = 0;
    for (; i < arr.length; ++i) {
      res.push(fn(arr[i], i));
    }
    arr = null;
    return res;
  },
  /** Checks and Return if the prop is Objects own Property */
  hasOwnProp: function(obj, val) {
    return Object.prototype.hasOwnProperty.call(obj, val);
  },
  /** Extend properties from extending Object to initial Object */
  extend: function(newObj, oldObj) {
    if (this.isDefined(newObj) && this.isDefined(oldObj)) {
      for (var prop in oldObj) {
        if (this.hasOwnProp(oldObj, prop)) {
          newObj[prop] = oldObj[prop];
        }
      }
      return newObj;
    } else {
      return newObj || oldObj || {};
    }
  }
};

// This Method will create Multiple functions in the Sys object that can be used to test type of
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
.forEach(
  function(name) {
    Sys['is' + name] = function(obj) {
      return toString.call(obj) == '[object ' + name + ']';
    };
  }
);
<h1>Use the Helper JavaScript Methods..</h1>
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>

Pour le module CommonJs exportable ou le module RequireJS ....

"use strict";

/*** Helper Utils ***/

/**
 * @description Util file :: From Vault
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

var Sys = {};

Sys = {
    isEmptyObject: function(val){
        return this.isObject(val) && Object.keys(val).length;
    },
    /** This Returns Object Type */
    getType: function(val){
        return Object.prototype.toString.call(val);
    },
    /** This Checks and Return if Object is Defined */
    isDefined: function(val){
        return val !== void 0 || typeof val !== 'undefined';
    },
    /** Run a Map on an Array **/
    map: function(arr,fn){
        var res = [], i=0;
        for( ; i<arr.length; ++i){
            res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
    },
    /** Checks and Return if the prop is Objects own Property */
    hasOwnProp: function(obj, val){
        return Object.prototype.hasOwnProperty.call(obj, val);
    },
    /** Extend properties from extending Object to initial Object */
    extend: function(newObj, oldObj){
        if(this.isDefined(newObj) && this.isDefined(oldObj)){
            for(var prop in oldObj){
                if(this.hasOwnProp(oldObj, prop)){
                    newObj[prop] = oldObj[prop];
                }
            }
            return newObj;
        }else {
            return newObj || oldObj || {};
        }
    }
};

/**
 * This isn't Required but just makes WebStorm color Code Better :D
 * */
Sys.isObject
    = Sys.isArguments
    = Sys.isFunction
    = Sys.isString
    = Sys.isArray
    = Sys.isUndefined
    = Sys.isDate
    = Sys.isNumber
    = Sys.isRegExp
    = "";

/** This Method will create Multiple functions in the Sys object that can be used to test type of **/

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
    .forEach(
        function(name) {
            Sys['is' + name] = function(obj) {
                return toString.call(obj) == '[object ' + name + ']';
            };
        }
    );


module.exports = Sys;

Actuellement utilisé sur un référentiel git public. Projet Github

Vous pouvez maintenant importer ce code Sys dans un fichier Sys.js. alors vous pouvez utiliser ces fonctions d'objet Sys pour découvrir le type d'objets JavaScript

vous pouvez également vérifier si l'objet est défini ou si le type est fonction ou l'objet est vide ... etc.

  • Sys.isObject
  • Sys.isArguments
  • Sys.isFunction
  • Sys.isString
  • Sys.isArray
  • Sys.isUndefined
  • Sys.isDate
  • Sys.isNumber
  • Sys.isRegExp

Par exemple

var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);

console.log(Sys.isDefined(jQuery));

1

En JavaScript, tout est un objet

console.log(type of({}))  //Object
console.log(type of([]))  //Object

Pour obtenir le type réel , utilisez ceci

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

J'espère que cela t'aides

En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.