Check if a value is an object in JavaScript

后端 未结 30 3785
臣服心动
臣服心动 2020-11-22 05:06

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

30条回答
  •  一整个雨季
    2020-11-22 05:57

    My God, too much confusion in other answers.

    Short Answer

    typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array)

    To test this simply run the following statements in chrome console.

    Case 1.

    var anyVar = {};
    typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // true
    

    Case 2.

    anyVar = [];
    typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array) // false
    

    Case 3.

    anyVar = null;
    typeof anyVar == 'object' && anyVar instanceof Object && !(anyVar instanceof Array); // false
    

    Explanation

    Okay.Let's break it down

    typeof anyVar == 'object' is returned true from three candidates - [], {} and null,

    anyVar instanceof Object narrows down these candidates to two - [], {}

    !(anyVar instanceof Array) narrows to only one - {}

    Drum rolls please!

    By this you may have already learnt how to check for Array in Javascript.

提交回复
热议问题