Home >Web Front-end >JS Tutorial >The method of finding the maximum and minimum values of an array is applicable to any array_javascript skills
The method of finding the maximum and minimum values of an array is applicable to any array_javascript skills
WBOYOriginal
2016-05-16 17:25:341129browse
Today I will share with you a method, this method is for arrays. In our daily work, we may have a headache when encountering array problems. In particular, let's find the maximum and minimum values from oddly shaped arrays. Although a method for finding the maximum and minimum values of an array has been introduced before, that method is only used for arrays that contain numbers.
Next, the method I introduce is applicable to any array. This method will pick out the values in the array and compare them. Html code:
/* getMinMax method to get the maximum and minimum values arr array Get the array of the maximum and minimum values num number can pass big or small return number If the parameter is big, it will return the maximum value, and if small, it will return the minimum value */ function getMinMax (arr,num) { var big = parseInt(arr[0]), small = parseInt( arr[0]), i = 0, al = arr.length;
for( i = 0; i < al; i ) { if(parseInt(arr [i]) > big) { big = parseInt(arr[i])
} else if(parseInt(arr[i]) < small) { small = parseInt( arr[i]); } } if (num=="big") return big; else if (num=="small") return small; } //Click to display, the maximum value 12 or the minimum value 4 will appear document.getElementById("inpu").onclick = function () { this.parentNode.innerHTML = "2. Maximum and minimum values The values are: " getMinMax (arr, "big") ", " getMinMax (arr, "small"); } }
Preview effect:
The above is the maximum and minimum array method I shared. Hope it helps everyone. If you have any suggestions, we can communicate at any time. ~
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn