检查javascript数组值是不是空的

时间:2014-06-17 21:44:37

标签: javascript json

我有点困惑,检查一个数组值是否从json响应中清空。

{
  "status": "success",
  "message": "All pages re-ordered",
  "content": {
    "_wysihtml5_mode": "1",
    "Page": {
        "title": "cover",
        "page_text": "dfvdfvdfvdfvdv story go daddy xxx",
        "storyborad_img": "1jhkjh.png",
        "background_url": "kjbj.png",
        "newBackground_url": "",
        "text_font": "arial",
        "id": "30",
        "book_id": "38",
        "newStoryborad_img": {
            "name": "1jhkjh.png",
            "type": "image\/png",
            "tmp_name": "\/Applications\/MAMP\/tmp\/php\/phpvyf8Xx",
            "error": 0,
            "size": 185607
        }
    },
    "User": {
        "username": "testuser"
    }
  }
}

我试图检查typeof array == undefined.length,但两个都给了我在else语句newBackground_url

中的内容
var page = $.parseJSON(xhr.responseText.replace('</p>', ''));
var imageType;
if(page.content.Page.newStoryborad_img.length > 0) {
    imageType = page.content.Page.newStoryborad_img.name;
}
else {
    imageType = page.content.Page.newBackground_url.name;
}

1 个答案:

答案 0 :(得分:2)

这取决于。根据您的示例,您将返回一个对象"newStoryborad_img": {...}

在这种情况下,您可以使用typeof(page.content.Page.newStoryborad_img) != 'undefined'

演示类型:http://jsfiddle.net/gunderjt/cn2cs/

但是如果你正在寻找一个数组的对象"newStoryborad_img": [{...}](注意括号)。然后检查数组中是否存在任何对象(假设您返回一个空数组)

page.content.Page.newStoryborad_img.length > 0将是您想要的

演示长度:http://jsfiddle.net/gunderjt/cn2cs/1/