我一生都无法弄清楚为什么indexOf无法找到数组中的数字。它不断返回-1。我的目标是禁止一个名词并将其放入禁止数组列表中,该列表必须是唯一的。所以数组中的每个元素都必须不同。因为我一直得到 -1,所以我的 while 循环永远不会执行。
谁能向我解释一下我做错了什么!
if( useA < 101 && totalAs < 5){
article1Num = 4; // A
noun1Num = [Math.floor(Math.random() * 5)];
//^^^ random number to try use
//--------
// Code to check if number is ban
alert("Test Noun1Num is " + noun1Num);
alert(bannedNounsTest.indexOf(noun1Num));
//^^^^ITS ALWAYS -1 !!!!!!! EVEN if there is a match!
while (bannedNounsTest.indexOf(parseInt(noun1Num)) >= 0 ) {
// ^^^searching the value of the current noun in ban, -1 if none
alert("In Loop and noun1Num is " + noun1Num);
noun1Num = [Math.floor(Math.random() * 5)];
// ^^looking for new number not in index while
}
//----------
bannedNounsTest.push(noun1Num); // put in ban list
totalAs++;
最佳答案
它给出 -1,因为这是 indexOf
在找不到匹配项时返回的结果。 (它不能,因为您正在搜索匹配的数组与数字)
你想要的是...
noun1Num = Math.floor(Math.random() * 5);
关于javascript - indexOf 不断返回 -1 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775447/