【问题标题】:Length of a JSON object [duplicate]JSON对象的长度[重复]
【发布时间】:2011-03-15 13:58:16
【问题描述】:

这个函数正在生成一个带有 json 对象的数组:

var estoque={};
function unpack_estoque(tnm,total,estoque_vl,id,tid,st) {
    tnm=tnm.split("|");
    total=total.split("|");
    estoque_vl=estoque_vl.split("|");
    id=typeof id != 'undefined' ? id.split("|") : null;
    tid=typeof tid != 'undefined' ? tid.split("|") : null;
    st=typeof st != 'undefined' ? st.split("|") : null;

    for (var i in tnm)
        estoque[i]={
            "id": id != null ? id[i] : null,
            "tid": tid != null ? tid[i] : null,
            "total": total[i],
            "estoque": estoque_vl[i],
            "tnm": tnm[i],
            "st": st != null ? st[i] : null
        };
}

现在我如何获得estoque 长度来循环收集的项目?

estoque.length 返回 undefinedfor (var i in estoque) 循环通过 JSON 对象而不是 estoque[] 根数组。

谢谢。

【问题讨论】:

  • 忘记所有那些复杂的方法,使用这个:Object.keys(estoque).length
  • 伟大的方法德里克!不过,请注意,此方法与 IE 8 不兼容。

标签: javascript json


【解决方案1】:
var estoque = {}; //object estoque.length will not work (length is an array function)
var estoque = new Array(); //estoque.length will work

你可以试试:

 var estoque = new Array();
 for (var i in tnm)
    estoque.push({
        "id": id != null ? id[i] : null,
        "tid": tid != null ? tid[i] : null,
        "total": total[i],
        "estoque": estoque_vl[i],
        "tnm": tnm[i],
        "st": st != null ? st[i] : null
    });

现在 estoque 将是一个数组(您可以将其作为一个遍历)。

【讨论】:

    【解决方案2】:

    你不会让它工作,因为它是一个数组方法,而不是一个对象。您可以使用 tnm 的长度属性作为度量。然后你可以使用:

    var tnmLength = tnm.length;
    for (i=0, i>tnmLength - 1; i++) {
         estoque[tnm[i]] = {};
    }
    

    循环遍历 tnm 数组中的所有项目。

    【讨论】:

      【解决方案3】:
      a={a:{},b:{},c:{}}
      Object.keys(a).length
      3
      

      【讨论】:

        猜你喜欢
        • 2017-10-04
        • 2017-03-30
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2011-08-01
        • 2011-03-21
        • 2011-07-28
        相关资源
        最近更新 更多