【问题标题】:Finding the min index in the array javascript在数组javascript中查找最小索引
【发布时间】:2021-03-14 12:48:35
【问题描述】:
var myArray = [];
let maxNum = 15;



function findMin(A, start, end){

  var result = Math.min.apply(null, myArray)
  console.log(result)

  return 0;
}

这个函数应该找到数组 A 中最小值的索引,查看从索引开始到索引结束的所有值。这包括开头和结尾的数字。

返回最小值出现的索引。

例如,如果 A = [3,2,1,6,4] findMax(A, 0,4) 应该返回 2,因为最小值为 1,并且它出现在该数组中的位置 2。

如何找到最小数的索引?

(myArray已经随机生成数组中的数字,只是不知道如何找到数组中最小数字的索引)

【问题讨论】:

  • 你可以使用indexOf吗?
  • 有很多方法可以做到这一点,互联网上有很多关于这个的内容。看来你开始学javascript了,建议你不要使用内置函数。

标签: javascript


【解决方案1】:

您可以结合使用 Math.min 和展开语法

const arr = [3,2,1,6,4]
const index = arr.indexOf(Math.min(...arr))

console.log(index) // 2

【讨论】:

    【解决方案2】:

    您可以使用您的最小值的indexOf()。或者您使用 forEach 手动遍历数组并记住最小值和它的索引。

    【讨论】:

      【解决方案3】:

      有两种方法:-手动和js函数

      1. JS函数:

        return A.indexOf(Math.min.apply(Math, A));

      2. 手册:

        通过他的数组循环会更快。

      【讨论】:

        【解决方案4】:

        这是你要找的东西吗

        var ary = [1,6,8,2,0,8,9]
         function findMin(A, start, end) {
           var finalAry = A.slice(start, end);
           var result = Math.min.apply(null, finalAry)
           return A.indexOf(result);
         }
        

        【讨论】:

          【解决方案5】:

          数组原型indexOf 返回数组中值的第一个索引。首先,您需要找到起始索引和结束索引之间的最小值。这就是我们使用slice 的原因,它返回一个子数组。

          数组示例slice

          const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
          
          console.log(animals.slice(1, 3));
          // slice will return the items from index 1 to upto 3
          // expected output: Array ["bison", "camel"] 
          

          那么我们要做的就是找到最小值并返回indexOf

          function findMin(A, start, end){
            let minValue = Math.min.apply(A.slice(start, end))
            return A.indexOf(Math.min.apply(Math, A));
          }
          
          let A = [3,2,1,6,4]
          console.log( findMin( A, 0, 4) )
          

          我们也可以使用 ES6 箭头函数来表达同样的功能。

          const findMin = (A, start, end) => A.indexOf(Math.min.apply(Math, A))
          
          let A = [3,2,1,6,4]
          console.log( findMin( A, 0, 4) )
          

          【讨论】:

          • 请考虑解释您的答案如何解决问题。
          【解决方案6】:

          试试这个方法。

          let myArray = [5,3,4,1,9];
          let maxNum = 15;
          
          function findMin(A, start, end){
          
            let result = Math.min.apply(null, myArray)
            console.log(myArray.indexOf(result))
          }
          
          findMin(myArray, 0, myArray.length)
          

          【讨论】:

            猜你喜欢
            • 2015-12-15
            • 2017-08-13
            • 2016-08-25
            • 2019-01-12
            • 2017-11-05
            • 2013-11-02
            • 2021-11-06
            • 2011-07-14
            • 2014-03-05
            相关资源
            最近更新 更多