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

时间:2018-10-17 13:37:37

标签: javascript undefined javascript-objects equality is-empty

我正在尝试测试对象的“空值”值。换句话说,如果对象的属性没有值,或仅包含空格值,则将其视为空。

我提到了这篇文章

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

,发现了一些有用的东西可以尝试。我最喜欢的那个使用JSON.stringify作为一个衬里。我不确定我是否确切了解它是如何工作的-我认为当控制台从中输出一对{}大括号表示它找到了一个对象,但也许还有更多细微差别?

如果可能的话,我想避免编写自定义函数或导入任何库。

这是一个MVP代码示例,用于演示我遇到的错误。请注意,最右边的两个 TD 元素显示为空,但其中包含选项卡。在此代码之后,我包括了我尝试过的“空空”逻辑测试及其结果:

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>

这是第3和第4 TD的屏幕截图。如您所见,项目3显示了innerText值,但是项目4没有文本,只有TAB字符。但是,他们都测试相同。

enter image description here

注意:

建议将此帖子How do I test for an empty JavaScript object?作为可能的重复内容。我希望是,但不是。此外,我尝试使用评分最高的答案,使用Pre-ECMA 5解决方案以获得最大的兼容性,但无济于事。实现该功能无效。我将在不久后使用最少的可验证代码进行更新...

代码尝试2:

在这种尝试中,我尝试了两个不同的功能来测试一个空对象。就像我已经说过的那样,我的对象不一定是空的,但它们可能包含空格字符。我从第一个示例中删除了许多调试程序,以使其更加精确,更小。

这是我使用的功能

ECMA 5之前的版本

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

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

ECMA 5

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

  return false;
}
同样,这些功能

起作用。这是此尝试的完整代码示例:

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>

1 个答案:

答案 0 :(得分:0)

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

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

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

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

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