Check if a value is an object in JavaScript

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

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

30条回答
  •  温柔的废话
    2020-11-22 05:42

    The Ramda functional library has a wonderful function for detecting JavaScript types.

    Paraphrasing the full function:

    function type(val) {
      return val === null      ? 'Null'      :
             val === undefined ? 'Undefined' :
             Object.prototype.toString.call(val).slice(8, -1);
    }
    

    I had to laugh when I realized how simple and beautiful the solution was.

    Example usage from Ramda documentation:

    R.type({}); //=> "Object"
    R.type(1); //=> "Number"
    R.type(false); //=> "Boolean"
    R.type('s'); //=> "String"
    R.type(null); //=> "Null"
    R.type([]); //=> "Array"
    R.type(/[A-z]/); //=> "RegExp"
    R.type(() => {}); //=> "Function"
    R.type(undefined); //=> "Undefined"
    

提交回复
热议问题