如何检查参数['可以是变量']是否在数组中

How to check if a parameter['which can be variable'] is in the array?

本文关键字:变量 是否 数组 参数 检查 何检查      更新时间:2023-09-26

我在这个freecodecamp问题,我必须添加或减去一个全局变量。条件是

  1. 如果参数为2,3,4,5,6,则必须添加1。
  2. 如果参数为7,8,9,则不加减0。
  3. 如果参数为10,则J,Q,K,A减去1(-1)。

我将条件放在函数内部的数组中。我不知道如何检查形参/实参是否为字符串。

这是我的代码。它期望输出'5 bet',但我有'4 bet'的输出:

var count = 0;
function cc(card) {
// Only change code below this line
var plusOne = [2,3,4,5,6]; // <- +1 if the argument is here
var zero = [7,8,9]; // <- 0 if the argument is here
var negative =[10,'J','Q','K','A']; // <- -1 if the argument is here
if(plusOne.indexOf(card)) {
count+=1; 
} else if(zero.indexOf(card)) {
count+=0;
} else if(negative.indexof(card)) {
count+=-1;
}
// return count output
if(count>1) {
output = count + ' Bet'; //<- global
return output.toString();
} else { //<-- if below zero
output = count + ' Hold';
return output.toString();
}

// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(4); cc(5); cc(6); //<-- call

javascript编译器

indexOf()的作用

indexOf()返回项目在数组中的位置,如果它在那里,则返回一个整数,如果不在,则返回-1。文档

你的错误

当你试图找到卡片2时,indexOf()将返回它的位置作为索引0,因为它是数组中的第一个元素。

索引0被if语句强制转换为布尔值,if语句为false。因此少了一个加法,你得到的结果是4 Bet而不是5 Bet

你应该怎么做

检查indexOf()的元素未找到条件,返回-1