JS how to infer whether an object {} is an empty object, no matter what property

Source: Internet
Author: User

JS how to infer whether an object {} is an empty object, no matter what property

Some time ago with JS wrote a similar "Angularjs" for data binding things, the function is relatively simple,

Usually it should come in an array of ArrayList JSON objects,

But sometimes a JSON object is returned through an Ajax method call, not an array!

The following code is used in order to be compatible with this situation:

if (typeof model.rows = = = = "Object" &&! Model.rows instanceof Array) {model.rows = [model.rows];}
This code found a bug in the process of later use, that is, when
Model.rows = {};
, it is still treated as a valid object, data binding, it can be imagined that all the data is empty.

How to resolve:

So how do we solve the problem?

The first habit is to search first, but the results are DOM-related, passable!

This reminds me of the way I wrote the properties of the JS object, which can be used here!

The code is as follows:

if (typeof model.rows = = = = "Object" &&! Model.rows instanceof Array) {var hasprop = False;for (var prop in model.rows) {hasprop = True;break;} if (hasprop) {model.rows = [model.rows];} Else{throw "Model.rows is empty object"; return false;}}
The code is very easy, do not write stare.



JS how to infer whether an object {} is an empty object, no matter what property

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.