7

使用 jQuery,我如何遍历一个对象,并通过每个值的计数来获取键的唯一值?

例如,对于这个数组:

var electrons = [
    { name: 'Electron1', distance: 1 }, 
    { name: 'Electron2', distance: 1 }, 
    { name: 'Electron3', distance: 2 }, 
    { name: 'Electron4', distance: 2 }, 
    { name: 'Electron5', distance: 2 }, 
    { name: 'Electron6', distance: 2 }, 
    { name: 'Electron7', distance: 2 }, 
    { name: 'Electron8', distance: 2 }, 
    { name: 'Electron9', distance: 2 }, 
    { name: 'Electron10', distance: 2 }, 
    { name: 'Electron11', distance: 3 }, 
];

我想找回以下内容:

var distance_counts = {1: 2, 2: 8, 3: 1};

我有这个,它有效,但有点笨拙:

var radius_counts = {};
for (var i = 0; i < electrons.length; i++) { 
    if (electrons[i].distance in radius_counts) { 
         radius_counts[electrons[i].distance] += 1;
    } else { 
         radius_counts[electrons[i].distance] = 1;
    } 
}
4

1 回答 1

8

您可以将map用于此目的:

var distances = {};
$.map(electrons,function(e,i) {
   distances[e.distance] = (distances[e.distance] || 0) + 1;
});

或者

var distances = {};
$.each(electrons,function(i,e) {
   distances[this.distance] = (distances[this.distance] || 0) + 1;
});

我还可以向您指出,虽然这段代码看起来不错且紧凑,但这通常不会更快。更好地使您的代码更快,更易于查看:

var distances = {},e;
for (var i = 0,l=electrons.length; i < l; i++) { 
    e = electrons[i];
    distances[e.distance] = (distances[e.distance] || 0) + 1;
}
于 2012-09-07T14:12:29.160 回答