RyanStephen提出了一个问题:Return index of greatest value in an array,或许与您遇到的问题类似。
回答者Ryan给出了该问题的处理方式:
This is probably the best way, since it’s reliable and works on old browsers:
function indexOfMax(arr) {
if (arr.length === 0) {
return -1;
}
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
There’s also this one-liner:
var i = arr.indexOf(Math.max(...arr));
It performs twice as many comparisons as is necessary and will throw a RangeError on large arrays, though. I’d stick to the function.
希望本文对你有帮助,欢迎支持JavaScript中文网