如何编写一个函数来查找数组中最大整数的索引?



>我正在尝试编写一个函数来查找数组中最大数字的索引,但是我当前的函数因数组中存在负数而中断。这是我到目前为止的代码。

export let maxIndex = (a: number[]): number => {
let biggest = -9000000000; // use to keep track of largest element
if (a.length === 0) {
return -1;
} else {
for (let i = 0; i < a.length; i++) {
if (a[i] > biggest) {
biggest = a[i]; 
}
}
}
return a[biggest]; 
};

你的return a[biggest];返回找到的最大元素索引处的数字(例如,[0, 2, 4, 6]将返回解析为undefineda[6],这对于您要完成的任务没有意义(。

您不仅需要跟踪到目前为止找到的最大数字,还需要跟踪最后找到的最大数字的索引。此外,如果将索引变量初始化为-1,则无需进行初始if测试:

const maxIndex = (a) => {
let biggestNum = -Infinity; // use to keep track of largest element
let biggestIndex = -1;
for (let i = 0; i < a.length; i++) {
if (a[i] > biggestNum) {
biggestNum = a[i]; 
biggestIndex = i;
}
}
return biggestIndex;
};
console.log(maxIndex([0, -1, -2]));
console.log(maxIndex([]));
console.log(maxIndex([30, 50, 40]));

另一种方法是传播到Math.max

const maxIndex = (a) => {
const max = Math.max(...a);
return a.indexOf(max);
};
console.log(maxIndex([0, -1, -2]));
console.log(maxIndex([]));
console.log(maxIndex([30, 50, 40]));

最新更新