jquery对象属性值平均值

时间:2016-04-13 10:18:39

标签: javascript jquery

我有以下对象:

rating {
     atmosphere: 85
     cleanliness: 91
     facilities: 91
     staff: 85
     security: 94
     location: 78
     valueForMoney: 85
    }

如何获得所有属性值的平均值?

  $.each( json.rating, function( key, value) {
    console.log( key + ": " + value);

  });

7 个答案:

答案 0 :(得分:2)

没有jquery函数。你必须手动完成

var count = 0;
var sum = 0;
$.each(rating, function(k, v){
   count++;
   sum += v;
});

var average = sum / count;

答案 1 :(得分:1)

您可以循环访问对象的属性以获取总值,然后将其除以对象本身中的数字或属性:

var total = 0;
for (var key in json.rating) {
    total += json.rating[key];
}
console.log(total / Object.keys(json.rating).length);

Working example

答案 2 :(得分:0)

您发布的对象无效,我已将其修改为有效对象,这是一个工作代码段



var json = {
  rating: {
    atmosphere: 85,
    cleanliness: 91,
    facilities: 91,
    staff: 85,
    security: 94,
    location: 78,
    valueForMoney: 85,
  }
}
var average = 0;
var counter = 0;

$.each(json.rating, function(key, value) {
  average += value;
  counter++;
});

document.write(average / counter);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

请看一下:

var rating  = {
     atmosphere: 85,
     cleanliness: 91,
     facilities: 91,
     staff: 85,
     security: 94,
     location: 78,
     valueForMoney: 85
    };

var totalCount = 0;
var totalSum = 0;
for(var key in rating){
  totalCount++;
  totalSum += rating[key];
}

$(".avg").text(totalSum/totalCount);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Average is: <div class="avg"></div>

答案 4 :(得分:0)

您可以将值相加并除以属性的长度。

&#13;
&#13;
var rating = { atmosphere: 85, cleanliness: 91, facilities: 91, staff: 85, security: 94, location: 78, valueForMoney: 85 },
    keys = Object.keys(rating),
    average = keys.reduce(function (r, k) {
        return r + rating[k];
    }, 0) / keys.length;

document.write(average);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

var tot = 0;
$.each( json.rating, function( key, value) {
    tot += value;
});
var avg = tot / Object.keys(json.rating).length

答案 6 :(得分:-1)

var sum = 0, len=1;

for (var key in rating) {
  sum += rating[key];
  len++;
}

var avg = sum / len;