indexOf 不断返回 -1 Javascript
indexOf keeps returning -1 Javascript
我这辈子都弄不明白为什么 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
returns。 (它不能,因为你正在搜索匹配的数组与数字)
你想要的是...
noun1Num = Math.floor(Math.random() * 5);
我这辈子都弄不明白为什么 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
returns。 (它不能,因为你正在搜索匹配的数组与数字)
你想要的是...
noun1Num = Math.floor(Math.random() * 5);