如题所示,开始敲代码
- 方案一:给数组先排序(由大到小排序),第一项就是最大值,最后一项是最小值
let ary = [12, 13, 14, 23, 24, 13, 15, 12];
let max = ary.sort((a, b) => b - a)[0];
let min = ary.sort((a, b) => b - a)[ary.length - 1];
console.log(max, min); // 24 12
- 方案二:假设第一个值是最大值/最小值,依次遍历数组中后面的每一项,和假设的值进行比较,如果比假设的值要大/小,把当前项赋值给MAX/MIN
let ary = [12, 13, 14, 23, 24, 13, 15, 12];
let max = ary[0],
min = ary[0];
for (let i = 1; i < ary.length; i++) {
let item = ary[i];
item > max ? max = item : null;
item < min ? min = item : null;
}
console.log(max, min); // 24 12
-
方案三:基于
Math.max/Math.min
配合apply
完成
let ary = [12, 13, 14, 23, 24, 13, 15, 12];
let max = Math.max.apply(null,ary);
let min = Math.min.apply(null,ary)
console.log(max, min); // 24 12
-
方案四:基于
Math.max/Math.min
配合eval
完成
let ary = [12, 13, 14, 23, 24, 13, 15, 12];
let max = eval("Math.max("+ary.join()+")");
let min = eval("Math.min("+ary.join()+")");
console.log(max, min); // 24 12
-
方案五:基于
Math.max/Math.min
配合ES6展开运算符完成
let ary = [12, 13, 14, 23, 24, 13, 15, 12];
let max = Math.max(...ary);
let min = Math.min(...ary)
console.log(max, min); // 24 12
网友评论