Determining whether the object is empty, determining whether the object contains a key-value pair


Today met, to sum up their own!

Determine whether the object is empty

To a null object

let obj = {}
  1. This does not work, all objects will be labeled as "[object Object]" string
obj.toString()
"[object Object]"
  1. This is not possible. .
obj.length
undefined
  1. Returns true if the circulation target is not empty
var b = function() {
for(var key in obj) {
return true;
}
return false;
}
console.log(b());//true
  1. If the object into a string, "{}" object
JSON.stringify(obj)
"{}"
  1. The object into a longitudinal array of re-determination
// Object.keys()ES5 引入了Object.keys方法,返回一个数组,成员是参数对象自身的
//(不含继承的)所有可遍历( enumerable )属性的键名。
Object.keys(obj)
[]
// Object.values方法返回一个数组,成员是参数对象自身的
//(不含继承的)所有可遍历( enumerable )属性的键值。正好与Object.keys相对接
Object.values(obj)
[]
// Object.entries方法返回一个数组,成员是参数对象自身的
//(不含继承的)所有可遍历( enumerable )属性的键值对数组。
Object.entries(obj)
[]
  1. This method is a method using getOwnPropertyNames Object object, acquired object attribute name, stored into an array, the return array object, we can determine whether the object is empty by determining the length of the array.
Object.getOwnPropertyNames(obj)
[]
  1. jQuery method of determining, dependent jquery
var b = $.isEmptyObject(data);
console.log(b) // true

Determining whether the object contains a key-value pair

The object is found

let obj = {a:1}
  1. hasOwnProperty method, which is a property used to detect the presence or absence of an object
obj.hasOwnProperty("a")
true
  1. ES6 property name in the object and returns a Boolean value
"a" in obj
true
  1. After transfer into an array is determined by the method of the array
Object.keys(obj).indexOf("a")
0

Etc. methods. . . .
Later encounteredto sum up

  1. Type determination value is a NaN
// 全局方法
isNaN('需要判断的值')
//返回类型为 boolean
  1. Type typeof returnsString
Published 50 original articles · won praise 23 · views 1227

Guess you like

Origin blog.csdn.net/qq_44698161/article/details/103299546