【问题标题】:In JavaScript how would I create a variable to go through an array and remember not only the highest value but also the position of that value在 JavaScript 中,我将如何创建一个变量来遍历数组,并且不仅要记住最大值,还要记住该值的位置
【发布时间】:2021-06-21 19:29:11
【问题描述】:
var array = [1,2,3,4,5];
for(i = 0; i < array.length; i ++){

}

这是我对它的理解程度(不是我的实际代码只是一个示例)以及我将如何使用这个 for 循环遍历数组,然后不仅记住最高值,而且记住它所在的位置。我想在我的代码中具体做的是创建一个点系统,它增加数组中不同位置编号的值,然后对它们进行排序以找到最高值,并取决于数组中的哪个位置/变量具有最高值会做一些不同的事情。为语法道歉。

【问题讨论】:

标签: javascript arrays variables assign


【解决方案1】:

您可以编写一个函数来跟踪具有最高值的索引max,并在arr[i] 更大时更新它 -

function goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(arr)
{ if (arr.length == 0) return false
  let max = 0
  for (let i = 1; i < arr.length; i++)
    if (arr[i] > arr[max])
      max = i
  return { highestValue: arr[max], positionOfThatValue: max }
}

const input1 =
  [ 1, 6, 4, 3, 9, 5, 8, 7 ]
  
const input2 =
  []

console.log(goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(input1))
// { highestValue: 9, positionOfThatValue: 4 }

console.log(goThroughAnArrayAndRememberNotOnlyTheHighestValueButAlsoThePositionOfThatValue(input2))
// false

【讨论】:

    【解决方案2】:

    只需使用array.reduce method

    var myArray = [0,1,2,12,3,4,5]
     
    const f_MaxPos = arr => arr.reduce((r,c,i)=>
      {
      if (!i || c > r.max)
        {
        r.max = c 
        r.pos = i
        } 
      return r
      }, { max:undefined, pos:-1 })
     
    
    console.log( JSON.stringify( f_MaxPos( myArray ) ) )
     
    .as-console-wrapper {max-height: 100%!important;top:0}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2015-01-23
      • 2013-09-02
      • 2012-07-10
      相关资源
      最近更新 更多