我正在尝试检查每个“旋转”是否存在奖金乘数的重复项,我尝试了几种不同的方法来遍历spunBonuses数组,但似乎无法获得它来获取如果给定数组对象多次出现,则该函数返回true。
下面是我当前的代码,有更好的方法吗?
(使用TypeScipt)
let spinAmount = 0;
let spunNumbers = [];
let spunBonuses = [];
let safeNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let safeBonuses = [15, 16, 17, 18, 19, 20];
let count15 = 0, count16 = 0, count17 = 0, count18 = 0, count19 = 0, count20 = 0;
let bonusNumber = null;
function getSpin() {
let numberSpun = null;
let bonusSpun = null;
let randomSafeNumber = Math.floor(Math.random() * safeNumbers.length)
numberSpun = safeNumbers[randomSafeNumber];
safeNumbers.splice(randomSafeNumber, 1);
bonusSpun = safeBonuses[Math.floor(Math.random() * safeBonuses.length)];
spunBonuses.push(bonusSpun);
if (bonusSpun == 15) {
count15 += 1;
} else if (bonusSpun == 16) {
count16 += 1;
} else if (bonusSpun == 17) {
count17 += 1;
} else if (bonusSpun == 18) {
count18 += 1;
} else if (bonusSpun == 19) {
count19 += 1;
} else if (bonusSpun == 20) {
count20 += 1;
}
}
while (spinAmount < 4) {
if (count15 < 2 && count16 < 2 && count17 < 2 && count18 < 2 && count19 < 2 && count20 < 2) {
getSpin();
spinAmount += 1;
} else { spinAmount = 4; }
}
if (count15 == 2) {
bonusNumber = 15;
} else if (count16 == 2) {
bonusNumber = 16;
} else if (count17 == 2) {
bonusNumber = 17;
} else if (count18 == 2) {
bonusNumber = 18;
} else if (count19 == 2) {
bonusNumber = 19;
} else if (count20 == 2) {
bonusNumber = 20;
}
console.log("Bonus achieved: " + bonusNumber);
答案 0 :(得分:0)
您可以使用map
,它是一个键值数据结构-仅保存唯一的键。
以这个为例:
let list: number[] = [1, 2, 3,4,5,6,2,3];
let myMap = new Map();
for(var i=0;i<list.length;i++)
{
if(myMap.has(list[i]))
myMap.set(list[i],myMap.get(list[i])+1);
else
myMap.set(list[i],1);
}
for (let entry of myMap.entries()) {
console.log(entry[0], entry[1]);
}
我在这里做什么:
1.首先遍历整个数组,然后通过检查它们是否已在地图中(如果存在)将它们插入地图,然后得到该元素的当前计数并对其进行递增用1代替,否则我插入带有1的元素。
2.最后,我要打印键(数组的所有元素),值(它们出现的次数)
因此,要完成所需的操作,您现在可以循环遍历map的值,看看是否有任何计数大于1,然后相应地返回,或者您可以存储相应的键以知道哪个元素在重复
。