简体   繁体   English

如何检查 object 是否为空?

[英]How to check whether an object is empty?

I'm learing JavaScript.我正在学习 JavaScript。 I cannot grasp the idea of an empty object.我无法理解空 object 的概念。 As I understand, there are situations when I need to check a variable whether it holds an object and has a value.据我了解,在某些情况下,我需要检查变量是否包含 object 并具有值。

So far, I know that a variable can be undefined .到目前为止,我知道一个变量可以是undefined

var car; // the value is undefined, as well as the type (which is it? number, array, etc.)

I also know, that everything that has a value, is true :我也知道,所有有价值的东西都是真的

var car = "Opel";
Boolean(car); // true 

And anything without a value is false:任何没有值的东西都是假的:

var car = ""; // typeof string, but it is empty, so
Boolean(car); // false
Boolean(null); // false 

So why doesn't it work the same way with arrays and objects?那么为什么它与 arrays 和对象的工作方式不同呢? Why is all of this true ?为什么这一切都是真的 Shouldn't empty arrays and objects return false ?不应该清空 arrays 并且对象返回false吗?

var car = {make: "Opel", year: 2015};
Boolean(car); // true
car = {};
Boolean(car); // true
car = ["BMW", "Opel"]; 
Boolean(car); // true
car = [];
Boolean(car); // true

Now I see that there are methods, that can be applied to check an object's length, I just haven't reached that part yet.现在我看到有一些方法可以用来检查对象的长度,但我还没有达到那个部分。

I'm learning at W3Schools website and this bit just got me puzzled:我正在 W3Schools 网站上学习,这让我很困惑:

But you cannot test if an object is null, because this will throw an error if the object is undefined:但是您无法测试 object 是否为 null,因为如果 object 未定义,这将引发错误:

Incorrect:不正确:

if (myObj === null) 

To solve this problem, you must test if an object is not null, and not undefined.要解决此问题,您必须测试 object 是否不是 null,并且不是未定义的。

But this can still throw an error:但这仍然会引发错误:

Incorrect:不正确:

if (myObj !== null && typeof myObj !== "undefined")

Because of this, you must test for not undefined before you can test for not null:因此,您必须先测试 not undefined,然后才能测试 not null:

Correct:正确的:

if (typeof myObj !== "undefined" && myObj !== null)

I still cannot understand the last line here.我仍然无法理解这里的最后一行。

Checking if an object is empty:检查object 是否为空:

Object.keys(yourObject).length
var car = {};
var isEmpty = Object.entries(car).length > 0; //false

var car = {make: "Opel", year: 2015};
var isEmpty = Object.entries(car).length > 0; //true

This should solve your problem, if your curious about the utility function Object.entries you can look on mdn这应该可以解决您的问题,如果您对实用程序 function Object.entries 感到好奇,您可以查看mdn

You can check wheather a object is empty or not in this simple way.您可以通过这种简单的方式检查 object 是否为空。

function objectLength( object ) {
    return Object.keys(object).length;
}

if(objectLength(yourObject) == 0){ 
    //object is empty
}else{
    //object not empty 
}

I would always use typeof myvar !== 'undefined' and checks for content myvar !== '' This would always would have a clear result.我总是使用typeof myvar !== 'undefined'并检查内容myvar !== ''这总是会有一个明确的结果。

There are concepts which are Truthy and Falsy values in JavaScript. JavaScript 中有一些概念是真值和假值。 I highly recommend you to read MDN documents about this issue.我强烈建议您阅读有关此问题的 MDN 文档。

All values are truthy unless they are defined as falsy (ie, except for false, 0, -0, 0n, "", null, undefined, and NaN).所有值都是真值,除非它们被定义为假(即,除了假、0、-0、0n、“”、null、未定义和 NaN)。

Truthy values真实的价值观

Falsy values虚假值

No, they should not be false.不,它们不应该是假的。

All objects are 'truthy', in that they return true when evaluated as a Boolean.所有对象都是“真实的”,因为它们在评估为 Boolean 时返回 true。 In Javascript, all arrays are objects (try console.log(typeof []) ), so they also return true, regardless of whether or not they are empty.在 Javascript 中,所有 arrays 都是对象(试试console.log(typeof []) ),所以它们也返回 true,不管它们是否为空。

To check if any array is empty:要检查任何数组是否为空:

if (MYARRAY.length === 0) {
  // console.log(true);
}

To check if an object is empty:检查 object 是否为空:

if (Object.keys(MYOBJECT).length === 0) {
  // console.log(true);
}

You can use您可以使用

  if ($('#element').is(':empty')){
  //do something
  }

OR或者

function isEmpty( el ){
      return !$.trim(el.html())
  }
  if (isEmpty($('#element'))) {
      // do something
  }

Here are some examples: http://api.jquery.com/is/以下是一些示例: http://api.jquery.com/is/

But if you need it in JavaScript:但如果你在 JavaScript 中需要它:

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

You can simply use typeof您可以简单地使用 typeof

I also know, that everything that has a value, is true我也知道,一切有价值的东西都是真的

I wouldn't say that.我不会这么说的。 All the examples given are values , even undefined and null are predefined values in JavaScript.给出的所有示例都是,甚至是undefined的, null是 JavaScript 中的预定义值。

Shouldn't empty arrays and objects return false?不应该清空 arrays 并且对象返回 false 吗?

It is like that by specification.规范就是这样。 And that is really the answer to your question.这确实是您问题的答案。 It is a choice made by the designers of the language.这是语言设计者做出的选择。

You could find some logic in it though.不过,您可以从中找到一些逻辑。 In JavaScript, values representing objects (and so also arrays) are references .在 JavaScript 中,表示对象(以及数组)的值是引用 These references are memory addresses/pointers, and although you cannot find out what exactly those addresses are, these are non-zero, even when an object has no properties.这些引用是 memory 地址/指针,尽管您无法找出这些地址到底是什么,但即使 object 没有属性,这些地址也不为零。

Note that your example objects ( {} and [] ) still have some non-enumerable properties, such a __proto__ and (for array) length , so they are not really as empty as you think.请注意,您的示例对象( {}[] )仍然具有一些不可枚举的属性,例如__proto__和(对于数组) length ,因此它们并不像您想象的那么空。

The most empty object you can create, is: Object.create(null)可以创建的最空的 object 是: Object.create(null)

Checking if an object is empty:检查 object 是否为空:

Reflect.ownKeys(car).length

Returns an array with one element when a Symbol is used as the key:Symbol用作键时,返回一个包含一个元素的数组:

let key = Symbol('vin')
let car = { [key]: 'honda' }
Reflect.ownKeys(car).length // => 1

Whereas Object.keys returns an array with zero elements in this case:Object.keys在这种情况下返回一个元素为零的数组:

let key = Symbol('vin')
let car = { [key]: 'honda' }
Object.keys(car).length // => 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM