Home  >  Article  >  Web Front-end  >  How to get the largest value in an array using JS

How to get the largest value in an array using JS

迷茫
迷茫Original
2017-03-26 16:50:451481browse

Get the maximum value in an array in JS

//取出数组中最大的值
	var arrs = [11,152,21,5,31,23,90,102];
	/*
		1、定义一个变量num
		2、让num的初始值是等于数组的第一个值
		3、拿num去和数组中的每一个值做比较,如果num小于arr[i],那就让num = arr[i]
		4、开始动手实现
	*/

	function max(arr){
		var num = arr[0];
		for(var i=0;i<arr.length;i++){
			if(num < arr[i]){
				num = arr[i]
			}
		}
		return num;
	}
	console.log(max(arrs))//152

The above is the detailed content of How to get the largest value in an array using JS. For more information, please follow other related articles on the PHP Chinese website!

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