可以先把思路理一下:
取出数组当中的最大值且在数组中的位置:
<script>
var array = [3,1,99,-66,55]
// 将数组第一个元素的值赋给arrayFirst
var arrayFirst = [0];
// 使用for 循环从数组第一个值开始做遍历
for (var index = 0; index < array.length; index++) {
// 如果元素当前值大于arrayFirst,就把这个当前值赋值给arrayFirst
if(arrayFirst<array[index]){
arrayFirst=array[index]
}
}
console.log(arrayFirst);//99
console.log(array.indexOf(arrayFirst));//2
</script>
取出最大值:for循环性能要比forEach()差,那可以将上面的方法改成forEach()方法:
<script> Array.prototype.max = function () { var max = this[0]; this.forEach(function (ele, index, arr) { if (ele > max) { max = ele; } }) return max; } var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56]; arr.max(); // 234 console.log(arr.max())//234 </script>
<script> Array.prototype.min = function () { var min = this[0]; this.forEach(function (ele, index, arr) { if (ele < min) { min = ele; } }) return min; } var arr = [9, 45, 23, 3, 6, 2, 7, 234, 56]; arr.min(); // 2 console.log(arr.min());//2 </script>
除了上面的方案,还可以有其他方法,比如使用数组的reduce()方法。回忆前面的学过的知识,reduce()方法可以接收一个回调函数callbackfn,可以在这个回调函数中拿数组中的初始值(preValue)与数组中当前被处理的数组项(curValue)做比较,如果preValue大于curValue值返回preValue,反之返回curValue值,依此类推取出数组中最大值:
<script> Array.prototype.max = function () { return this.reduce(function (preValue, curValue, index, array) { return preValue > curValue ? preValue : curValue; }) } var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56]; arr.max(); // 234 console.log(arr.max())// 234 </script>
Function.prototype.apply()让你可以使用提供的this与参数组与的数组来调用参数。<script>
// 取出数组中最大值
Array.max = function (array) {
return Math.max.apply(Math, array);
};
// 取出数组中最小值
Array.min = function (array) {
return Math.min.apply(Math, array);
};
var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56];
Array.max(arr); // 234
Array.min(arr); // 1
console.log(Array.max(arr))// 234
console.log(Array.min(arr))// 1
</script>
Math对象也是一个对象,可以使用对象的字面量来写,如:
<script> Array.prototype.max = function () { return Math.max.apply({}, this); } Array.prototype.min = function () { return Math.min.apply({}, this); } var arr = [1, 45, 23, 3, 6, 2, 7, 234, 56]; arr.max(); // 234 arr.min(); // 1 console.log(arr.max());// 234 console.log(arr.min())// 1 </script>
附加参考网址:
https://www.cnblogs.com/jiechen/p/5521490.html
http://www.w3cplus.com/javascript/array-part-8.html
原文:https://www.cnblogs.com/huanghuali/p/9782357.html