可能重复:
在jquery中查找数组的长度(大小)
我有一个从php文件返回的json对象,如下所示: -
{"food":[
{
"name" :"Belgian Waffles",
"price" :"$5.95",
"description":"two of our famous Belgian Waffles with plenty of real maple syrup",
"calories" :"650"
},
{
"name" :"Strawberry Belgian Waffles",
"price" :"$7.95",
"description":"light Belgian waffles covered with strawberries and whipped cream",
"calories" :"900"
},
{
"name" :"Berry-Berry Belgian Waffles",
"price" :"$8.95",
"description":"light Belgian waffles covered with an assortment of fresh berries and whipped cream",
"calories" :"900"
}
]}
Run Code Online (Sandbox Code Playgroud)
这基本上是从物体中返回三个食物元素.如果json数据是动态的并且使用jquery不知道,如何计算返回的元素总数?
nnn*_*nnn 16
假设您已经解析了JSON(或者jQuery已经为您完成了它,如果您使用它的Ajax函数将会这样做)并且您将结果对象放在变量中,只需执行以下操作:
var data = /* your parsed JSON here */
var numberOfElements = data.food.length;
Run Code Online (Sandbox Code Playgroud)
(注意:没有JSON对象这样的东西:在解析JSON之前它是一个字符串;在你解析它之后它就是一个对象.)
编辑:在评论,你说你不会知道属性被称为food-如果你不知道会有一个确切属性和属性将是一个数组,你可以这样做:
var data = /* your object */
var propName;
var numberOfElements;
for (propName in data);
numberOfElements = propName ? data[propName].length : 0;
Run Code Online (Sandbox Code Playgroud)
如果您不知道将只有一个属性,那么您的要求太模糊:如果可能有多个属性,您想要检查其长度?
var json = '{"food":[{"name":"Belgian Waffles","price":"$5.95","description":"two of our famous Belgian Waffles with plenty of real maple syrup","calories":"650"},{"name":"Strawberry Belgian Waffles","price":"$7.95","description":"light Belgian waffles covered with strawberries and whipped cream","calories":"900"},{"name":"Berry-Berry Belgian Waffles","price":"$8.95","description":"light Belgian waffles covered with an assortment of fresh berries and whipped cream","calories":"900"}]}';
var obj = JSON.parse(json);
alert(obj.food.length);?
Run Code Online (Sandbox Code Playgroud)
请注意,IE8及以下版本没有JSON的原生支持,但有一个polyfill可用.
另外,作为另一个注释,jQuery没有在这里做工作 - 这只是普通的旧javascript.
| 归档时间: |
|
| 查看次数: |
56876 次 |
| 最近记录: |