【发布时间】:2021-01-16 07:34:07
【问题描述】:
该函数仅在 first (arr[0]) 或 last index ( arr[arr.length-1]) 的数组。如何修复逻辑错误?
function isGreater(arr) {
let a = arr[0];
for (let i = 0; i < arr.length; i++) {
var isGreat = (a < arr[i]) ? arr[i] : a;
}
return isGreat;
}
console.log(isGreater([7, 9, 10000, 11, 25, 20]));
// output=> 20, expected output 10000
console.log(isGreater([7, 11, 25, 2]));
// output=> 7, expected output 25
【问题讨论】:
-
试试
Math.max.apply(null, [7, 9, 10000, 11, 25, 20])。 -
Math.max.apply(null, [7, 9, 10000, 11, 25, 20])但无论如何,你需要有一个变量,在循环之前设置为 0,在每个循环中设置为自身或当前数组元素中的较大者。 -
我认为使用扩展运算符比使用
Function.prototype.apply更干净。在这种情况下,Math.max(...[7, 9, 10000, 11, 25, 20])最终,浏览器之间的性能会有所不同,并且两者都可能导致大型数组的堆栈溢出,因此这确实是个人喜好问题。
标签: javascript arrays logic