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.

4
  • 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. Commented Dec 30, 2017 at 8:56
  • In addition, you check for an array using Array.isArray(arr) Commented Dec 30, 2017 at 9:13
  • Have a look at various ways to detect plain objects. Basically just use Object.getPrototypeOf(obj) == Object.prototype. Do not use the deprecated __proto__ getter. Commented Dec 30, 2017 at 10:55
  • OK.Thank you!I will have a try. Commented Dec 30, 2017 at 14:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.