How to compare a variable by its type? For example, if this number is one, and if it is a string, then another, if the object, then the third?
1 answer
Use the typeof and instanceof operators (their differences are written here ):
var data; data = ...; if (typeof data === 'string') { // строка } if (typeof data === 'number') { // число } if (data instanceof Array) { // массив } if (data instanceof Object) { // объект / словарь } - With an array is not so simple. Need to use
Array.isArray. - user207618 - @Other, in most cases,
instanceofwill do the same? - Qwertiy ♦ - There is a nuance with null. - Qwertiy ♦
|