如何獲取一組數字並使用JavaScript中的reduce函數返回最高和最低數字?如何獲取一組數字並使用Javascript中的reduce函數返回最高和最低數字
我迄今嘗試:
function each(collection, callback) {
if(Array.isArray(collection)) {
for(var i = 0; i < collection.length; i++) {
callback(collection[i]);
}
} else {
for(var prop in collection) {
callback(collection[prop]);
}
}
}
function reduce(collection, callback, initial) {
each(collection, function(element) {
if(initial === undefined) {
initial = element;
} else {
initial = callback(initial, element);
}
});
return initial;
}
function highAndLow(collection) {
//use reduce
return reduce(collection, function(initial, element){
if(initial[element] > initial[element]){
initial = "high: " + element;
} else {
initial = "low: " + element
}
return initial;
}, {})
}
highAndLow([5,2,1,6,8])
結果應該是這樣的: highAndLow(5,2,1,6,8)=== {低:1,高:8}