对于简单数组,我们直接使用indexOf最为简洁美观。

var a = [1,2,3,4,5,6,7,7,6,5,4,3,2,1];

// for循环
var indexOfMax = 0;
var tempMax = a[0];
for(let i = 0; i < a.length; i ++){
    if(a[i] > tempMax){
        tempMax = a[i];
        indexOfMax = i;
    }
}

// indexOf
var max = Math.max(...a);
var indexOfMax = a.indexOf(max);

// reduce
var indexOfMax = 0;
var max = a.reduce( (a,c,i) => c > a ? (indexOfMax = i,c) : a, 0)

实际项目中,我们遇到大量数组都是复杂数组,内部包含对象,而我们需要根据对象的一个字段进行找最大值的索引。此时indexOf行不通了,使用reduce最为简洁。

// json格式
var a = [
    {"sid":11478,"floor":1,"x":14,"y":78,"points":5463},
    {"sid":13256,"floor":1,"x":32,"y":56,"points":9463}, 
    {"sid":24765,"floor":1,"x":47,"y":65,"points":3256}, 
    {"sid":48352,"floor":1,"x":83,"y":52,"points":7946}, 
    {"sid":28643,"floor":1,"x":86,"y":43,"points":6492}
]

// 找出points最大对象所在的索引
var indexOfMax = 0;
var max = a.reduce( (a,c,i) => c.points > a ? (indexOfMax = i,c.points) : a, 0)

除了普通对象,内含数组也很常见,用法与上一致。

// csv格式
var a = [
    [11478,1,14,78,5463],
    [13256,1,32,56,9463],
    [17356,1,28,73,6319],
    [75863,1,57,63,4257]
]

// 找出points最大对象所在的索引
var indexOfMax = 0;
var max = a.reduce( (a,c,i) => c[4] > a ? (indexOfMax = i,c[4]) : a, 0)