Check if a value is an object in JavaScript

2018-12-31 21:21发布

How do you check if a value is an Object in JavaScript?

30条回答
低头抚发
2楼-- · 2018-12-31 21:40

Return Types

typeof JavaScript constructors and objects (including null) returns "object"

console.log(typeof null, typeof [], typeof {})

Checking on Their constructors

Checking on their constructor property returns function with their names.

console.log(({}).constructor) // returns a function with name "Object"
console.log(([]).constructor) // returns a function with name "Array"
console.log((null).constructor) //throws an error because null does not actually have a property

Introducing Function.name

Function.name returns a readonly name of a function or "anonymous" for closures.

console.log(({}).constructor.name) // returns "Object"
console.log(([]).constructor.name) // returns "Array"
console.log((null).constructor.name) //throws an error because null does not actually have a property

Final code

function isAnObject(obj)
{
    if(obj==null) return false;
    return obj.constructor.name.toLowerCase() === "object"
}

console.log(isAnObject({})) // return true
console.log(isAnObject([])) // returns false
console.log(isAnObject(null)) // return false

Note: Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

查看更多
公子世无双
3楼-- · 2018-12-31 21:41

Ready to use functions for checking

function isObject(o) {
  return null != o && 
    typeof o === 'object' && 
    Object.prototype.toString.call(o) === '[object Object]';
}

function isDerivedObject(o) {
  return !isObject(o) && 
    null != o && 
    (typeof o === 'object' || typeof o === 'function') &&
    /^\[object /.test(Object.prototype.toString.call(o));
}

// Loose equality operator (==) is intentionally used to check
// for undefined too

// Also note that, even null is an object, within isDerivedObject
// function we skip that and always return false for null

Explanation

  • In Javascript, null, Object, Array, Date and functions are all objects. Although, null is bit contrived. So, it's better to check for the null first, to detect it's not null.

  • Checking for typeof o === 'object' guarantees that o is an object. Without this check, Object.prototype.toString would be meaningless, since it would return object for everthing, even for undefined and null! For example: toString(undefined) returns [object Undefined]!

    After typeof o === 'object' check, toString.call(o) is a great method to check whether o is an object, a derived object like Array, Date or a function.

  • In isDerivedObject function, it checks for the o is a function. Because, function also an object, that's why it's there. If it didn't do that, function will return as false. Example: isDerivedObject(function() {}) would return false, however now it returns true.

  • One can always change the definition of what is an object. So, one can change these functions accordingly.


Tests

function isObject(o) {
  return null != o && 
    typeof o === 'object' && 
    Object.prototype.toString.call(o) === '[object Object]';
}

function isDerivedObject(o) {
  return !isObject(o) && 
    null != o && 
    (typeof o === 'object' || typeof o === 'function') &&
    /^\[object /.test(Object.prototype.toString.call(o));
}

// TESTS

// is null an object?

console.log(
  'is null an object?', isObject(null)
);

console.log(
  'is null a derived object?', isDerivedObject(null)
);

// is 1234 an object?

console.log(
  'is 1234 an object?', isObject(1234)
);

console.log(
  'is 1234 a derived object?', isDerivedObject(1234)
);

// is new Number(1234) an object?

console.log(
  'is new Number(1234) an object?', isObject(new Number(1234))
);

console.log(
  'is new Number(1234) a derived object?', isDerivedObject(1234)
);

// is function object an object?

console.log(
  'is (new (function (){})) an object?', 
  isObject((new (function (){})))
);

console.log(
  'is (new (function (){})) a derived object?', 
  isObject((new (function (){})))
);

// is {} an object?

console.log(
  'is {} an object?', isObject({})
);

console.log(
  'is {} a derived object?', isDerivedObject({})
);

// is Array an object?

console.log(
  'is Array an object?',
  isObject([])
)

console.log(
  'is Array a derived object?',
  isDerivedObject([])
)

// is Date an object?

console.log(
  'is Date an object?', isObject(new Date())
);

console.log(
  'is Date a derived object?', isDerivedObject(new Date())
);

// is function an object?

console.log(
  'is function an object?', isObject(function(){})
);

console.log(
  'is function a derived object?', isDerivedObject(function(){})
);

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 21:43

use typeof(my_obj) will tells which type of variable it is.

if it is object will show 'object'

simple JS function,

function isObj(v) {
    return typeof(v) == "object"
}

Eg:

function isObj(v) {
    return typeof(v) == "object"
}

var samp_obj = {
   "a" : 1,
   "b" : 2,
   "c" : 3
}

var num = 10;
var txt = "Hello World!"
var_collection = [samp_obj, num, txt]
for (var i in var_collection) {
  if(isObj(var_collection[i])) {
     console.log("yes it is object")
  }
  else {
     console.log("No it is "+ typeof(var_collection[i]))
  }
}

查看更多
步步皆殇っ
5楼-- · 2018-12-31 21:44
var a = [1]
typeof a //"object"
a instanceof Object //true
a instanceof Array //true

var b ={a: 1}
b instanceof Object //true
b instanceof Array //false

var c = null
c instanceof Object //false
c instanceof Array //false

I was asked to provide more details. Most clean and understandable way of checking if our variable is an object is typeof myVar. It returns a string with a type (e.g. "object", "undefined").

Unfortunately either Array and null also have a type object. To take only real objects there is a need to check inheritance chain using instanceof operator. It will eliminate null, but Array has Object in inheritance chain.

So the solution is:

if (myVar instanceof Object && !(myVar instanceof Array)) {
  // code for objects
}
查看更多
无色无味的生活
6楼-- · 2018-12-31 21:44

If you are already using AngularJS then it has a built in method which will check if its an object (without accepting null).

angular.isObject(...)
查看更多
旧时光的记忆
7楼-- · 2018-12-31 21:47

I'm fond of simply:

function isObject (item) {
  return (typeof item === "object" && !Array.isArray(item) && item !== null);
}

If the item is a JS object, and it's not a JS array, and it's not null…if all three prove true, return true. If any of the three conditions fails, the && test will short-circuit and false will be returned. The null test can be omitted if desired (depending on how you use null).

DOCS:

http://devdocs.io/javascript/operators/typeof

http://devdocs.io/javascript/global_objects/object

http://devdocs.io/javascript/global_objects/array/isarray

http://devdocs.io/javascript/global_objects/null

查看更多
登录 后发表回答