How does js determine whether an object {} is an empty object without any attributes and js does not have any
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.
How can I determine if a java object in js is empty?
Step 1: Under check (), go directly to alert (obj); and check the value. By the way, test whether this method is available;
Step 2: alert (obj = null); alert (obj = ""); sometimes it is "". If there is no value, whether it is null, true, or "" is true.
Js checks whether the object is empty
// If it is an empty object var obj ={}; obj = false; // true // so it can be like this: if (obj) {// This means to forcibly convert obj to bool value, therefore, it will be converted to false and then judged in if/false} else {// true} // if obj is not an empty object var obj = {id: 1 }; obj = true; // true // Same principle as above