JavaScript finds the maximum value and index in the array


find the maximum


1. reduce() merge

var max=arr.reduce(fuction(pre,current,index,_arr){
    
    
	if(pre>current){
    
    
		current=pre;
	}
	return current;
})
console.log(max);

2. sort () sorting

var sortArr=arr.sort(function(a,b){
    
    
	return a-b;
})
console.log(sortArr[arr.lenght-1]);

3.Math.max()

var max=Math.max(...arr);
...收集符,扩展运算符,将运算符后面的变量里的东西每项拆下来
arr=["1","2","3"];
console.log(...arr);	//1 2 3

Find the maximum index


1.

console.log(arr.indexOf(max));

2. findIndex (callback function)

Arrow function:

function isMax(){
	return;
}
==>
var isMax=()=>{
	return;
};
//findIndex(回调函数)
var current=arr.findIndex((item)=>{
    
    
	return max==item;
})
console.log(current);

Guess you like

Origin blog.csdn.net/weixin_68915174/article/details/128470589