JS基础:求一组数中的最大最小值,以及所在位置


 1         var arr = [0, 5, -3, 6, 2, -6, 10];  2         //定义一个最大值和一个最小值,把他们的索引值赋值给固定的两个变量
 3         var maxValue = arr[0];  4         var minValue = arr[0];  5         var maxIndex = 0;  6         var minIndex = 0;  7         for (var i = 1; i < arr.length; i++) {  8             if(arr[i] > maxValue){  9                 //把这个元素赋值给最大值,把他对应的索引值,赋值给maxIndex
10                 maxValue = arr[i]; 11                 maxIndex = i; 12  } 13             //如果数组中的元素小于我们定义的最小值
14             if (arr[i] < minValue) { 15                 minValue = arr[i]; 16                 minIndex = i; 17  } 18  } 19  console.log(maxValue); 20  console.log(maxIndex); 21  console.log(minValue); 22         console.log(minIndex);

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM