编写一个名为“ json_average”的函数,该函数将JSON格式的字符串作为对象数组格式的参数,其中每个对象都有键“质量”,“密度”,“温度”和“速度”,并且每个对象键映射到浮点数。此函数应以JSON字符串的形式返回数组中所有对象的平均“速度”,格式为{“ velocity”:}
function json_average(JSON1){
var load = JSON.parse(JSON1);
var sum = 0;
var sum1 = 0;
var dictionary = {};
for (var i in load){
sum += i.velocity;
sum1 += 1;
}
var average = sum / sum1;
dictionary.velocity = average;
return JSON.stringify(dictionary);
}
console.log(json_average('[{"velocity": 1}, {"velocity": 10}]'));
我一直将'velocity'的值返回为null。我在做什么错了?
答案 0 :(得分:1)
因为它是一个数组,所以要使用for i of load
:
function json_average(JSON1) {
var load = JSON.parse(JSON1);
var sum = 0;
var sum1 = 0;
var dictionary = {};
for (var i of load) {
sum += i.velocity;
sum1 += 1;
}
var average = sum / sum1;
dictionary.velocity = average;
return JSON.stringify(dictionary);
}
console.log(json_average('[{"velocity": 1}, {"velocity": 10}]'));
for...in
用于迭代对象的键。