How to check if an argument is an object (and not an array) in JavaScript

后端 未结 3 812
既然无缘
既然无缘 2021-01-23 03:09

After testing out instasnceof I found that it will return true if the argument is an array or an object literal.

function test(options){
  if(option         


        
3条回答
  •  遥遥无期
    2021-01-23 03:43

    function isPlainObject(o) {
         return Object(o) === o && Object.getPrototypeOf(o) === Object.prototype;
    }
    

    However, you can't test wether o was declared as a literal or instantiated somehow else - you can just test whether it's a plain object without any constructor than Object.

提交回复
热议问题