Je veux pouvoir passer soit un littéral de chaîne,
'this is a string'
Ou un objet javascript
{one: 'this', two: 'is', three: 'a', four: 'string' }
Comme argument à une fonction, et prendre des actions différentes selon qu'il s'agisse d'une chaîne ou d'un objet. Comment puis-je déterminer ce qui est vrai?
Pour être spécifique, je veux faire itérer sur les propriétés d'un objet, et effectuer des analyses si une propriété est une chaîne, mais nidifier de manière récursive si la propriété est un objet. J'ai compris comment utiliser $.each()
pour itérer sur les propriétés de l'objet, mais si je fais simplement cela avec la chaîne, il traite la chaîne comme un tableau de lettres plutôt que comme une seule chose. Puis-je contourner cela d'une autre manière?
var data = { foo: "I'm a string literal", bar: { content: "I'm within an object" } };
JQuery
$.each(data, function(i, element){ if($.isPlainObject(element){ // we got an object here } });
Il existe des méthodes similaires comme $.isArray()
ou $.isFunction()
dans la libération jQuery.
Javascript actif
for(var element in data){ if(toString.call(element) === '[object Object]'){ // we got an object here } }
Pour utiliser la manière hack'ish
avec toString
a l'avantage, vous pouvez identifier si c'est really
un objet et un array
. Les deux, les objets et les tableaux renverraient l' object
en utilisant l' typeof element
.
Longue histoire, vous ne pouvez pas compter sur l'opérateur typeof
pour distinguer les objects
et les arrays
réels. Pour cela, vous avez besoin de toString.call()
. Si vous avez juste besoin de savoir s'il s'agit d'un objet ou non, typeof
est très bien.
var a = 'this is a string'; console.log(typeof a); // Displays: "string" var b = {one: 'this', two: 'is', three: 'a', four: 'string' }; console.log(typeof b); // Displays: "object"
Donc:
if (typeof yourArgument === 'string') { // Do the string parsing } else if (typeof yourArgument === 'object') { // Do the property enumeration } else { // Throw exception }
METTRE À JOUR:
Quelques considérations supplémentaires:
Voir le commentaire de @Andy E ci-dessous.
typeof null
returns "object"
également. Il en va de même pour tout autre objet, y compris les tableaux.
Essaye ça:
function some_function(argument) { if (typeof(argument) == "string" || argument.constructor == String) { // it's a string literal } else if (argument && typeof(argument) == "object" && argument.constructor != Array) { // it's an object and not null } else { // error } }
Merci à Andy E pour le tipp avec argument.constructor
.
Essayez l'opérateur typeof . Il renverra l' object
pour les objets et la string
pour les chaînes.
Vous pouvez faire quelque chose comme ça
function something(variableX){ if (typeof(variableX) === 'object'){ // Do something }else if (typeof(variableX) === 'string'){ // Do something } }
J'avais un problème similaire et je pensais avoir trouvé une solution. Voici mon exemple de code pour toute personne intéressée.
var propToDotSyntax = function (obj) { var parse = function (o, n) { var a = [], t; for (var p in o) { if (o.hasOwnProperty(p)) { t = o[p]; if (n !== undefined) tmp = n + '.' + p; else tmp = p; if (t && typeof(t) === 'object') a.push(arguments.callee(t, tmp)); else a.push(tmp + '=' + t); } } return a; }; return parse(obj).toString(); } var i = { prop: 'string', obj: { subprop: 'substring', subobj: { subsubprop: 'subsubstring' } } }; propToDotSyntax(i);
Cela passera par toutes les propriétés d'un objet – même si les propriétés sont des objets eux-mêmes – et renvoie une chaîne avec les valeurs suivantes dans la syntaxe des points.
"prop=string,obj.subprop=substring,obj.subobj.subsubprop=subsubstring"
J'ai eu l'inspiration de DavidPirek.com – Merci M. Pirek!