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);

 

posted @ 2018-04-12 18:18  叶子玉  阅读(2891)  评论(0编辑  收藏  举报