当前位置: 代码迷 >> Web开发 >> 计算JSON某个数据的数量解决思路
  详细解决方案

计算JSON某个数据的数量解决思路

热度:77   发布时间:2012-04-12 15:46:35.0
计算JSON某个数据的数量
JScript code

[
    {"id": 123, "type": "1"},
    {"id": 234, "type": "1"},
    {"id": 345, "type": "2"},
    {"id": 4646, "type": "2"},
    {"id": 878, "type": "2"},
    {"id": 78987, "type": "2"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
]



例如 怎么计算type=2有多少个

还有个问题怎么现在每天回贴都没分了。。。。

------解决方案--------------------
var arr = [
{"id": 123, "type": "1"},
{"id": 234, "type": "1"},
{"id": 345, "type": "2"},
{"id": 4646, "type": "2"},
{"id": 878, "type": "2"},
{"id": 78987, "type": "2"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
];

var count = 0;
for(var i = 0 ; i < arr.length ; i ++)
{
if(arr[i].type == '2') count ++
}
alert(count)

------解决方案--------------------
JScript code

var json = [
    {"id": 123, "type": "1"},
    {"id": 234, "type": "1"},
    {"id": 345, "type": "2"},
    {"id": 4646, "type": "2"},
    {"id": 878, "type": "2"},
    {"id": 78987, "type": "2"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
];
var count = 0;
for(var i=0;i<json.length;i++){
  count += json[i].type=="2"?1:0;
}
alert(count);

------解决方案--------------------
JScript code

Array.prototype.FindAll = function(fn){
    if(typeof(fn) === 'function'){
        ret = [];
        for(var i = 0, l = this.length; i<l; i++){
            var o = this[i];
            if(fn(o)) ret[ret.length] = o;
        }
        return ret;
    }
    return null;
}
var arr = 上面定义的那些数据;
alert(arr.FindAll(function(o){return o.type == "1";}).length); 
  相关解决方案