0

In my limited experience about object type judgment,I don't know how to judge whether a value is Object Literal in JavaScript? I am searching for a long time on net.But no use.Please help or try to give some ideas how to achieve this.Thanks in advance!

The solution is: As we know,we can use 'typeof' or 'instanceof' to judge the type of value. For example,to judge an Array,we can use:

var array=[0,1,2,3,4];
if(Object.prototype.toString.call(array)==='[object Array]'){
    alert('This is an Array!');
}

But now I want to check whether a value is Object Literal like this:

var obj={
    a:2
};

How to judge it? My way is:

if(obj["__proto__"]["constructor"]===Object){
    alert("This is Object Literal");
}

I am afraid this way is wrong.

LinWei
  • 7
  • 1
  • An object literal is a syntactical construct. It doesn't exist at runtime; at runtime, it's just an object, whether it was created as a literal or not. – Ingo Bürk Dec 30 '17 at 08:56
  • In addition, you check for an array using `Array.isArray(arr)` – baao Dec 30 '17 at 09:13
  • Have a look at [various ways to detect plain objects](https://stackoverflow.com/q/15315694/1048572). Basically just use `Object.getPrototypeOf(obj) == Object.prototype`. Do not use the deprecated `__proto__` getter. – Bergi Dec 30 '17 at 10:55
  • OK.Thank you!I will have a try. – LinWei Dec 30 '17 at 14:55

1 Answers1

0

You can check by matching the constructor property with Object like the following:

var obj={
    a:2
};
console.log(obj.constructor == Object); // true

var arr = [1,2,3];
console.log(arr.constructor == Object); // false
Mamun
  • 66,969
  • 9
  • 47
  • 59