Il typeof operatore non ci aiuta davvero a trovare il tipo reale di un oggetto.
Ho già visto il seguente codice:
Object.prototype.toString.apply(t)
Domanda:
È il modo più accurato di verificare il tipo di oggetto?
Il typeof operatore non ci aiuta davvero a trovare il tipo reale di un oggetto.
Ho già visto il seguente codice:
Object.prototype.toString.apply(t)
Domanda:
È il modo più accurato di verificare il tipo di oggetto?
Risposte:
La specifica JavaScript fornisce esattamente un modo corretto per determinare la classe di un oggetto:
Object.prototype.toString.call(t);
Object.prototype.toString.call(new FormData()) === "[object FormData]"che sarebbe vero. È inoltre possibile utilizzare slice(8, -1)per restituire FormDatainvece di[object FormData]
Object.prototypee {}?
Object.prototype.toString.call(new MyCustomObject())ritorna [object Object]mentre new MyCustomObject() instanceOf MyCustomObject returns trueè quello che volevo (Chrome 54.0.2840.99 m)
new MyCustomObject().constructor === MyCustomObject.
il Object.prototype.toStringè un buon modo, ma le prestazioni è il peggiore.
http://jsperf.com/check-js-type

Utilizzare typeofper risolvere alcuni problemi di base (String, Number, Boolean ...) e utilizzare Object.prototype.toStringper risolvere qualcosa di complesso (come Array, Date, RegExp).
e questa è la mia soluzione:
var type = (function(global) {
var cache = {};
return function(obj) {
var key;
return obj === null ? 'null' // null
: obj === global ? 'global' // window in browser or global in nodejs
: (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
: obj.nodeType ? 'object' // DOM element
: cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
|| (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
};
}(this));
usare come:
type(function(){}); // -> "function"
type([1, 2, 3]); // -> "array"
type(new Date()); // -> "date"
type({}); // -> "object"
typefunzione è buona, ma guarda come funziona rispetto ad alcune altre typefunzioni. http://jsperf.com/code-type-test-a-test
La risposta accettata è corretta, ma mi piace definire questa piccola utility nella maggior parte dei progetti che costruisco.
var types = {
'get': function(prop) {
return Object.prototype.toString.call(prop);
},
'null': '[object Null]',
'object': '[object Object]',
'array': '[object Array]',
'string': '[object String]',
'boolean': '[object Boolean]',
'number': '[object Number]',
'date': '[object Date]',
}
Usato così:
if(types.get(prop) == types.number) {
}
Se stai usando l'angolazione puoi anche farla iniettare in modo pulito:
angular.constant('types', types);
var o = ...
var proto = Object.getPrototypeOf(o);
proto === SomeThing;
Tieni sotto controllo il prototipo che prevedi abbia l'oggetto, quindi confronta con esso.
per esempio
var o = "someString";
var proto = Object.getPrototypeOf(o);
proto === String.prototype; // true
o instanceof String; //true?
"foo" instanceof Stringbreak
typeof(x)==='string'invece.
Object.getPrototypeOf(true)non riesce dove (true).constructorritorna Boolean.
Direi che la maggior parte delle soluzioni mostrate qui soffrono di un eccesso di ingegnere. Probabilmente il modo più semplice per verificare se un valore è di tipo [object Object]è verificare con la .constructorproprietà di esso:
function isObject (a) { return a != null && a.constructor === Object; }
o anche più breve con le funzioni freccia:
const isObject = a => a != null && a.constructor === Object;
La a != nullparte è necessaria perché si potrebbe passare nulloundefined e non è possibile estrarre una proprietà del costruttore da una di queste.
Funziona con qualsiasi oggetto creato tramite:
Objectcostruttore{}Un'altra caratteristica interessante è la sua capacità di fornire report corretti per le classi personalizzate che ne fanno uso Symbol.toStringTag. Per esempio:
class MimicObject {
get [Symbol.toStringTag]() {
return 'Object';
}
}
Il problema qui è che quando si chiama Object.prototype.toStringun'istanza di esso, [object Object]verrà restituito il rapporto falso :
let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]
Ma il controllo contro il costruttore dà un risultato corretto:
let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false
Il modo migliore per scoprire il tipo REAL di un oggetto (incluso ENTRAMBI il nome Object o DataType nativo (come String, Date, Number, ..etc) E il tipo REAL di un oggetto (anche quelli personalizzati); è afferrando la proprietà name del costruttore del prototipo dell'oggetto:
Tipo nativo Ex1:
var string1 = "Test";
console.log(string1.__proto__.constructor.name);
display:
String
Ex2:
var array1 = [];
console.log(array1.__proto__.constructor.name);
display:
Array
Classi personalizzate:
function CustomClass(){
console.log("Custom Class Object Created!");
}
var custom1 = new CustomClass();
console.log(custom1.__proto__.constructor.name);
display:
CustomClass
nullo undefined.
Vecchia domanda che conosco. Non è necessario convertirlo. Vedi questa funzione:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Esempi:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Basso costo e semplice.
falsese l'oggetto del test è nulloundefined
trueoppurefalse
false. In che modo questo aiuta a rispondere alla domanda?
Ho messo insieme una piccola utility di controllo del tipo ispirata alle risposte corrette sopra:
thetypeof = function(name) {
let obj = {};
obj.object = 'object Object'
obj.array = 'object Array'
obj.string = 'object String'
obj.boolean = 'object Boolean'
obj.number = 'object Number'
obj.type = Object.prototype.toString.call(name).slice(1, -1)
obj.name = Object.prototype.toString.call(name).slice(8, -1)
obj.is = (ofType) => {
ofType = ofType.toLowerCase();
return (obj.type === obj[ofType])? true: false
}
obj.isnt = (ofType) => {
ofType = ofType.toLowerCase();
return (obj.type !== obj[ofType])? true: false
}
obj.error = (ofType) => {
throw new TypeError(`The type of ${name} is ${obj.name}: `
+`it should be of type ${ofType}`)
}
return obj;
};
esempio:
if (thetypeof(prop).isnt('String')) thetypeof(prop).error('String')
if (thetypeof(prop).is('Number')) // do something
nullo undefinedo trueofalse