假设我在 cookie 文件中有以下 Json 表示一个简单的客户购物篮。
{"merc":[
{"id":"2","nrOfItems":"1"},
{"id":"4","nrOfItems":"2"}
]
}
现在假设我想确保 merch 不为空,在这种情况下我想打印出“your basket is empty”。我怎样才能做到这一点?我只知道如何使用 $.each 函数。
cookiee= readCookie("merchBasket");
object = cookiee.toString();
obj = JSON.parse(object);
if(Merch isn't empty){//How can I check the length of merch?
$.each(obj.merc, function() {
//Print out the merch
});
}
else{
document.getElementById("someDiv").innerHTML= "your basket is empty";
}
最佳答案
使用array.length
:
if(obj.merc.length > 0) {
// do whatever you want
}
关于javascript - 如何检查json中数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219010/