JSON对象的长度

时间:2010-07-13 21:41:47

标签: javascript json

此函数正在生成一个包含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返回undefined,而for (var i in estoque)循环通过JSON对象,而不是estoque []根数组。

感谢。

3 个答案:

答案 0 :(得分:2)

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将是一个数组(你可以作为一个数组遍历)。

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

a={a:{},b:{},c:{}}
Object.keys(a).length
3