通过函数选出数组中最大值和其索引;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> var a = [2,3,4,5,6,9,1,2,3] function max(a){ var c = a[0]; var b = 0; for(var k in a){ if(c<a[k]){ c = a[k] console.log(k) } } return c; } console.log(max(a)) </script> </body> </html>
另一种方法:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script> 9 var a = [2,3,4,5,6,9,1,2,3] 10 // function max(a){ 11 // var c = a[0]; 12 // var b = 0; 13 // for(var k in a){ 14 // if(c<a[k]){ 15 // c = a[k] 16 // console.log(k) 17 // } 18 // } 19 // return c; 20 21 // } 22 // console.log(max(a)) 23 Math.max.apply([],a) 24 console.log(a.indexOf(Math.max.apply([],a))) 25 26 </script> 27 </body> 28 </html>
坚持下去就能成功