我正在学习 JS,我正在制作一个应用程序来查找高尔夫比赛中每个洞的获胜者。杆数较少的球员是该洞的获胜者,但有时不止一名球员可以以相同的杆数将洞打平,因此,要找到该洞的获胜者,我需要评估并列球员的杆数下一个洞并打破平局,如果平局持续,我需要评估下一个洞等等。
函数 foo 应该返回一个数组,其中包含该洞的获胜者的索引、位置或名称(如果无法打破平局)。
这是我的代码:
var players = [
"Jug 1",
"Jug 2",
"Jug 3",
"Jug 4"
];
var arrHoyos = [
[4, 3, 3, 4],
[4, 5, 4, 5],
[4, 4, 5, 6]
];
function foo(array) {
var arrWinners = [];
//arrHoyos
for (var i = 0, len = array.length; i < len; i++) {
var arr = array[i];
var arr2 = array[(i + 1) % array.length];
var pos = 0;
var min = 0;
var tie = false;
var temp = [];
var temp2 = [];
min = Math.min.apply(null, arr);
//arr
for (var j = 0, len2 = arr.length; j < len2; j++) {
if (min == arr[j]) {
temp.push(arr.indexOf(min, j));
}
}
if (temp.length > 1) {
tie = true;
var counter = 0;
while (tie == true) {
for (var count = 0; count < temp.length; count++) {
pos = temp[count];
temp2[count] = arr2[pos];
}
min = Math.min.apply(null, temp2);
for (var count2 = 0; count2 < temp.length; count2++) {
if (temp2[count2] != min) {
temp.slice(count2, 1);
}
}
if (temp.length == 1 || counter == array.length) {
tie = false;
}
counter++;
}
}
arrWinners[i] = players[temp[0]];
console.log(temp, temp2);
console.log(arrWinners[i]);
}
}
foo(arrHoyos);
Chrome 控制台结果:
[1, 2] [5, 4]
Jug 2
[0, 2] [4, 5]
Jug 1
[0, 1] [4, 3]
Jug 1