我想编写一个函数,将数组的最大值和最小值相乘并返回该值。
arr = [12,6,10,26,3,24]
例如:
26*3 + 24*6 + 12*10 = 342
我有这样的代码:
function minSum(arr) {
var i;
var Result=0;
for (i = arr.lenght; i >= 0, i-2) { // I need the first help here
Result = Result + Math.max.apply(null,arr) * Math.min.apply(null,arr);
var indexMax = arr.indexOf(Math.max.apply(null,arr));
if(indexMax != -1) { // remove the current max value from the array.
arr.splice(indexMax, 1);
}
var indexMin = arr.indexOf(Math.min.apply(null,arr));
if(indexMin != -1) { // remove the current min value from the array.
arr.splice(indexMin, 1);
}
}
return; // need the second help here
}
所有代码都有效,所以我只需要完成循环部分和返回语句。我想循环直到数组为空*我喜欢这样结束*****也欢迎其他解决方案!
最佳答案
您可以通过先对数组进行排序来简化逻辑。
var arr = [12,6,10,26,3,24] ;
arr.sort(function(a,b){
return a-b;
});
var result = 0;
for (var i = 0; i < arr.length/2; i++) {
result += arr[i]*arr[arr.length - i -1];
}
console.log(result);
关于javascript - 做循环,直到数组中的元素在 Javascript 中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229471/