循环遍历包含整数值的json对象并选择最小值的最佳方法是什么?
例如,如果我有一个看起来像这样的对象
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
我想挑出3个最小的数字 - 在这种情况下1,2,3 - 最好的方法是什么?
答案 0 :(得分:1)
使用 for...in
循环将对象值放入数组中。然后使用 sort()
对其进行排序并获取值
更新:您可以使用 splice()
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
arr = [];
// array for storing values
for (var o in z)
// iterate over the array
arr.push(z[o]);
// push value to the array
document.write(arr
.sort()
// sorting the value array
.splice(0, 3)
// get first three values
.join()
// joining the 3 values
)

答案 1 :(得分:1)
您可以尝试以下脚本:
// create an array to store the values.
var numbers = [];
// loop through the keys of z and push each value in the numbers array.
for(var key in z){
numbers.push(z[key]);
}
// sort the array.
numbers = numbers.sort(function(a,b){ return a-b; });
// pick up the first three.
firstThree = numbers.slice(0,3);
var z =
{"a": 4,
"b":2,
"c":5,
"d":1,
"e":3
}
var numbers = [];
for(var key in z){
numbers.push(z[key]);
}
numbers = numbers.sort(function(a,b){ return a-b; });
firstThree = numbers.slice(0,3);
alert(firstThree)

答案 2 :(得分:0)
我建议迭代对象的键并使用键将值减小到最小值。
var z = {
"a": 4,
"b": 2,
"c": 5,
"d": 1,
"e": 3
},
smallest = Object.keys(z).reduce(function (r, k) {
return Math.min(r, z[k]);
}, Number.MAX_VALUE);
document.write(smallest);