繁体   English   中英

在 JavaScript 中,我将如何通过数组为 go 创建一个变量,不仅要记住最大值,还要记住该值的 position

[英]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

var array = [1,2,3,4,5];
for(i = 0; i < array.length; i ++){

}

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

您可以编写一个 function 来跟踪具有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

只需使用array.reduce 方法

 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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM