首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web开发 >

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

2012-04-12 
计算JSON某个数据的数量JScript code[{id: 123, type: 1},{id: 234, type: 1},{id: 345, t

计算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); 

热点排行