Sometimes we encounter such a situation: During the data verification process when some front-end controls submit data to the server, it is necessary to determine whether the submitted data is empty. If it is string data in an ordinary form, you only need to determine the length after trim. The data required here can be of various types (numbers, strings, arrays, objects, etc.), through JSON.stringify(data ) is serialized and then passed.
The following data values are defined here as "null values":
•undefined
•null
•Empty string and pure blank string: '', ' ' etc.
•Empty array: []
•Empty object: {}
For data values other than this, they are considered not to be empty.
Among them, null and undefined are easy to identify, but for other types, we need to get the data type before we can use the corresponding method to detect whether the data is empty. The easiest way to think of is to use the typeof operator:
Use instanceof? This can only judge objects, and there is a problem that multiple objects of the same type do not share prototypes when there are multiple frames. Objects obtained from other frames cannot be correctly judged.
Fortunately, there is another simplest and most reliable method: Object.prototype.toString. For different types of data, this method can return strings such as '[object Object]', '[object Array]', and '[object String]', which is very convenient for judgment. It should be noted that in IE8 and below browsers, this method will return '[object Object]' for null, undefined, window, etc., but fortunately, this does not affect our use of it to determine empty objects.
The code is directly below, and the explanation can be found in the comments.
var type;
if(value == null) { // Equivalent to value === undefined || value === null
return true;
}
type = Object. prototype.toString.call(value).slice(8, -1);
switch(type) {
case 'String':
return !$.trim(value);
case ' Array':
return !value.length; > ;