简体   繁体   English

如何测试JavaScript对象是否为空?

[英]How to test if JavaScript object is empty?

I'm trying to test for an "empty-ish" value of an object. 我正在尝试测试对象的“空值”值。 In other words, if the object's properties have no values, or contain only whitespace values, let's consider it empty. 换句话说,如果对象的属性没有值,或仅包含空格值,则将其视为空。

I referred to this post 我提到了这篇文章

https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty

and found some helpful things to try. 并找到了一些有用的尝试。 This one I liked the most uses JSON.stringify as a one liner. 我最喜欢的那个使用JSON.stringify作为一个衬里。 I'm not sure I understand exactly how it works -- I think when the console outputs a pair of {} curly braces from it means it found an object, but maybe there is more nuance than that? 我不确定我是否确切了解它是如何工作的-我认为,当控制台从中输出一对{}大括号时,表示它找到了一个对象,但是也许还有更多细微差别?

I want to avoid writing a custom function or importing any libraries if possible. 我想避免编写自定义函数或尽可能导入任何库。

Here is a MVP code example that demonstrates the error I am having. 这是一个MVP代码示例,用于演示我遇到的错误。 Notice the two TD elements on the far right appear empty, but they have tabs in them. 请注意,最右边的两个TD元素显示为空,但是其中有选项卡。 I include the logic tests for "empty-ish" that I tried and their results after this code: 在此代码之后,我包括了我尝试过的“空-ish”逻辑测试及其结果:

 console.clear(); // Set selector values var selectors = { blockSel: "td", titleSel: "span", urlSel: "" }; var styles = { // reddish text style1: "background: bisque; color: brown; font-weight: bold; margin-top: .2em; padding-top: .3em; border-top: solid red 3px;", style2: "background:aliceblue;", style3: "background:orange;", h2: "color: black; font-weight: 700; font-size: 1.2em;" }; var outObj = {}; // var titles = document.querySelectorAll('#res h3'); var blocks = document.querySelectorAll(selectors.blockSel); [...blocks].forEach(function(block, i) { // Debugging ... console.log("%cNumber %s", styles.style1, i); console.log("%c\\tVALUES:\\t\\t\\t", styles.h2); console.log("%cblock.innerText = %s", styles.style2, block.innerText); console.log( "%cJSON.stringify(block.innerText) = %s", styles.style2, JSON.stringify(block.innerText) ); console.log( "%cJSON.stringify(block.innerText.trim()) = %s", styles.style2, JSON.stringify(block.innerText.trim()) ); console.log("%c\\tTESTS:\\t\\t\\t", styles.h2); console.log( '%cJSON.stringify(block.innerText.trim()) == ""', styles.style3, JSON.stringify(block.innerText.trim()) == "" ); console.log( "%cJSON.stringify(block.innerText) !== undefined", styles.style3, JSON.stringify(block.innerText) !== undefined ); console.log( "%cJSON.stringify(block.innerText) != undefined", styles.style3, JSON.stringify(block.innerText) != undefined ); console.log( '%cJSON.stringify(block.innerText) != ""', styles.style3, JSON.stringify(block.innerText) != "" ); }); 
 body { background-position: center bottom; padding: 0px; margin: 0px; font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #000000; background-image: url('images/abstract_background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-color: #00111B; } td { background: #ffffb3; min-width: 13vw; text-align: center; } #description { color: white; font-size: 1.2em; max-width: 1024px; } 
 <div id="description"> <h2>DESCRIPTION</h2> <section> <h3>Purpose:</h3> <p>This pen demonstrates an issue I'm having with trying test for an "empty-ish" value of an object. In other words, if the object has no values, or contains only whitespace values, let's consider it empty. This isn't working so I'm posting my code to help me debug this issue.</p> <p>Please open the JavaScript console to view output</p> <h3>Errors</h3> <ul> <li>None.</li> </ul> </section> </div> <table> <tr> <td valign="top"> <div id="Archives1_DataList1_ctl40_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl40_Label2">January 17, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=1ca546d2-2e81-486c-b199-a3d056d157a2" target="_self"> <img id="Archives1_DataList1_ctl40_Image1" src="https://media.iadsnetwork.com/edition/1964/136061/resized/175_0_1964719d1738-a4a9-46a0-a45e-a1f9aadb7fa7.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td valign="top"> <div id="Archives1_DataList1_ctl41_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl41_Label2">January 10, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=cd43c968-1e66-4919-9f97-fc0fe69d749f" target="_self"> <img id="Archives1_DataList1_ctl41_Image1" src="https://media.iadsnetwork.com/edition/1964/135726/resized/175_0_19644b88f108-6e80-46d6-b7fb-d22f4cebac54.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td valign="top"> <div id="Archives1_DataList1_ctl42_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl42_Label2">January 3, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=fd6fb6f4-6b86-4489-a65f-eeb41d64eade" target="_self"> <img id="Archives1_DataList1_ctl42_Image1" src="https://media.iadsnetwork.com/edition/1964/135385/resized/175_0_1964a8b1cc88-08f4-49f0-ace1-ca84b8a26d55.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td></td> <td></td> </tr> </table> 

Here is a screenshot of the 3rd and 4th TD's. 这是第3和第4 TD的屏幕截图。 As you can see, item 3 shows an innerText value, but item 4 has no text, just a TAB character. 如您所见,项目3显示了innerText值,但是项目4没有文本,只有TAB字符。 But, they both test the same. 但是,他们都测试相同。

在此处输入图片说明

CAVEAT: 警告:

This post How do I test for an empty JavaScript object? 这篇文章我如何测试一个空的JavaScript对象? was suggested as a possible duplicate. 建议作为可能的重复项。 I wish it was, but it is not. 我希望是,但不是。 Further, I tried the top rated answer, using the Pre-ECMA 5 solution for maximum compatibility, to no avail. 此外,我尝试使用评分最高的答案,使用Pre-ECMA 5解决方案以获得最大的兼容性,但无济于事。 Implementing that function did not work. 实现该功能无效。 I will update with a minimum verifiable code shortly... 我将在短期内以最少的可验证代码更新...

Code Attempt 2: 代码尝试2:

In this attempt I try two different functions to test for an empty object. 在这种尝试中,我尝试了两种不同的功能来测试一个空对象。 Like I said already, my objects aren't necessarily empty, but they may contain whitespace characters. 就像我已经说过的那样,我的对象不一定是空的,但它们可能包含空格字符。 I've eliminated a lot of debugs from the first example to make this more precise and smaller. 我从第一个示例中消除了很多调试,以使其更加精确和小巧。

Here are the functions I used 这是我使用的功能

Pre-ECMA 5 ECMA 5前

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }

    return JSON.stringify(obj) === JSON.stringify({});
} 

ECMA 5 ECMA 5

function isEmpty2(obj) {
  if ( Object.keys(obj).length === 0 && obj.constructor === Object ) {
    return true;
  }

  return false;
}

Again, NEITHER of the these functions worked. 同样, 这些功能中的任何一个都起作用。 And here is the complete code example for this attempt: 这是此尝试的完整代码示例:

 console.clear(); var outObj = {}; var blocks = document.querySelectorAll('td'); [...blocks].forEach(function(block, i) { // Debugging ... console.log("%cNumber %s", styles.style1, 1+i); console.log(block); console.log("%cisEmpty(block) = %s", styles.style4, isEmpty(block)); console.log("%cisEmpty2(block) = %s", styles.style4, isEmpty2(block)); }); /* isEmpty() */ function isEmpty(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)) return false; } return JSON.stringify(obj) === JSON.stringify({}); } /* isEmpty2() */ function isEmpty2(obj) { if ( Object.keys(obj).length === 0 && obj.constructor === Object ) { return true; } return false; } 
 body { background-position: center bottom; padding: 0px; margin: 0px; font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #000000; background-image: url('images/abstract_background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-color: #00111B; } td { background: #ffffb3; min-width: 13vw; text-align: center; } #description { color: white; font-size: 1.2em; max-width: 1024px; } 
 <table> <tr> <td valign="top"> <div id="Archives1_DataList1_ctl40_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl40_Label2">January 17, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=1ca546d2-2e81-486c-b199-a3d056d157a2" target="_self"> <img id="Archives1_DataList1_ctl40_Image1" src="https://media.iadsnetwork.com/edition/1964/136061/resized/175_0_1964719d1738-a4a9-46a0-a45e-a1f9aadb7fa7.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td valign="top"> <div id="Archives1_DataList1_ctl41_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl41_Label2">January 10, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=cd43c968-1e66-4919-9f97-fc0fe69d749f" target="_self"> <img id="Archives1_DataList1_ctl41_Image1" src="https://media.iadsnetwork.com/edition/1964/135726/resized/175_0_19644b88f108-6e80-46d6-b7fb-d22f4cebac54.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td valign="top"> <div id="Archives1_DataList1_ctl42_div1" class="rlvI"> <div style="width: 175px; float: left; margin-bottom: 5px;"> <span id="Archives1_DataList1_ctl42_Label2">January 3, 2018</span> </div> <div> <a class="example7" href="/editionviewer/default.aspx?Edition=fd6fb6f4-6b86-4489-a65f-eeb41d64eade" target="_self"> <img id="Archives1_DataList1_ctl42_Image1" src="https://media.iadsnetwork.com/edition/1964/135385/resized/175_0_1964a8b1cc88-08f4-49f0-ace1-ca84b8a26d55.jpg" style="border-width:0px;"> </a> </div> </div> </td> <td></td> <td></td> </tr> </table> 

!!Object.getOwnPropertyNames({}).length => false !! Object.getOwnPropertyNames({})。length => false

!!Object.getOwnPropertyNames({a: 'abc'}).length => true !! Object.getOwnPropertyNames({a:'abc'})。length => true

============================================ ============================================

Object.getOwnPropertyNames({}).length => 0 Object.getOwnPropertyNames({})。length => 0

Object.getOwnPropertyNames({a: 'abc'}).length => 1 Object.getOwnPropertyNames({a:'abc'})。length => 1

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

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