How does js determine whether an object {} is an empty object without any attributes?
How does js determine whether an object {} is an empty object without any attributes?
Some time ago, I used js to write something similar to "angularjs" for data binding. The function is relatively simple,
Generally, an array of ArrayList JSON objects should be passed in,
However, sometimes AJAX calls return a JSON object instead of an array!
The following code is used to ensure compatibility:
If (typeof model. rows === "object "&&! (Model. rows instanceof Array) {model. rows = [model. rows];}
This code later found a Bug, that is, when
Model. rows = {};
It is still treated as a valid object for Data Binding. it is conceivable that all data is empty.
Solution:
So how can we solve this problem?
The first habit is to search, but the results are DOM-related and unsatisfactory!
This reminds me of the previous method for Traversing JS object attributes, 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 simple, so you don't need to write comments.