获取javascript中具有最高值的数组键

Ale*_*exa 12 javascript arrays jquery

我有一个类似的阵列

arr[1] = 234;
arr[2] = 345;
...

arr[40] = 126;
Run Code Online (Sandbox Code Playgroud)

如何在不重复数组的情况下获取具有最高值的元素的索引?

ken*_*bec 19

您可以应用Math.max并将数组作为其参数传递 -

arr.indexOf(Math.max.apply(window,arr))
Run Code Online (Sandbox Code Playgroud)

但是现在Math.max正在进行迭代,就像排序一样.

有人必须查看未排序数组中的每个项目......


Dar*_*evo 11

使用jQuery,就像:

// Get the max value from the array    
maxValue = Math.max.apply(this, arr);

// Get the index of the max value, through the built in function inArray
$.inArray(maxValue,arr);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 4

如果数组未排序,则无需迭代就无法执行此操作。