假设我宣布

var ad = {}; 

如何检查该对象是否包含用户定义的属性?


当前回答

ES6函数

/**
 * Returns true if an object is empty.
 * @param  {*} obj the object to test
 * @return {boolean} returns true if object is empty, otherwise returns false
 */
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0

例子:


let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false

其他回答

当确定对象是用户定义的对象时,确定UDO是否为空的最简单的方法是以下代码:

isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};

尽管这种方法(本质上)是一种演绎方法,-它是最快的,而且可能是最快的。

a={};
isEmpty(a) >> true

a.b=1
isEmpty(a) >> false 

注: 不要在浏览器定义的对象上使用它。

你可以使用内置的Object。方法获取对象上的键列表并测试其长度。

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length){
 // Your code here if x has some properties  
}

这个怎么样?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj
for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

成员是指成员属性,成员变量,你可以叫它>_>

上面的代码将返回EVERYTHING,包括toString… 如果你只想查看对象的原型是否被扩展:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

注A:我们检查虚拟对象的成员是否与测试对象的成员具有相同的类型。如果它是一个扩展,dummyobject的成员类型应该是"undefined"

ES6函数

/**
 * Returns true if an object is empty.
 * @param  {*} obj the object to test
 * @return {boolean} returns true if object is empty, otherwise returns false
 */
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0

例子:


let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false