【问题标题】:Checking if Json object is empty检查 Json 对象是否为空
【发布时间】:2015-10-12 10:52:58
【问题描述】:

我使用 Jquery 检查来自 ajax 调用的对象是否为空。

在这个例子中,我进行了正确的 AJAX 调用,它返回了一些数据。

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  [{"dateTime":"2015-10-02","entries":220}]
est if object is empty: false

但是在这个例子中我做了一个不正确的 AJAX 调用,它什么都不返回。

console.log ("obj before Json parse: ",response);
var test = $.isEmptyObject(response);
console.log("test if object is empty:",test);

obj before Json parse:  []
test if object is empty: false

在这种情况下,测试变量肯定应该为真,因为对象是空的?

【问题讨论】:

标签: javascript jquery object


【解决方案1】:

使用length检查对象是否为空。

var isEmpty = (response || []).length === 0;

【讨论】:

  • 我应该使用 response.length;然后。因为我刚刚测试了 isPlainObject 并且在这两种情况下都返回 false。
  • @AndreasUldallLeonhard isPlainObject 作用于对象,如果响应是数组,使用arr.length 检查它是否为空
  • 如果responsenullundefinedresponse.length 将抛出错误。你可以更具防御性并拥有var test = response && response.length
  • @user5325596 感谢您的案例,我已经更新了答案
  • 嗯,在 Json 解析之前,这对 obj 毫无意义: [{"dateTime":"2015-10-02","entries":220}] index.html:335 测试对象是否为empty: 41 obj before Json parse: [] test size of object: 2 这就是我在两者上都做 .length 时发生的情况
【解决方案2】:
var jsonData = JSON.parse(responseBody);
tests['empty_or_not'] = jsonData.length === 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2023-03-15
    • 2013-10-11
    • 2014-01-01
    相关资源
    最近更新 更多