[英]Count and compare elements in an array
playerArray
has seven elements. playerArray
具有七个元素。 I want to return true if whatever array is passed into hasEnoughPlayers is at least 7 and false if it isn't. 如果要传递给hasEnoughPlayers的任何数组至少为7,我想返回true,否则返回false。
I tried using playerArray.length - 1
. 我尝试使用
playerArray.length - 1
。 Still doesn't work. 仍然不起作用。
var hasEnoughPlayers = function(playerArray){
for (var i = 0; i < (playerArray.length - 1); i++){
if ((playerArray.length - 1) == 7){
return false;
}
else {
return true;
}
}
};
I keep getting a false or some error message. 我不断收到错误或错误消息。 Here is the code tested with a
team
array. 这是使用
team
数组测试的代码。
var hasEnoughPlayers = function(playerArray){
return playerArray.length === 7;
};
var team = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry Potter"];
console.log(hasEnoughPlayers(team));
Your doing i < (playerArray.length - 1) instead of i < (playerArray.length). 你在做我<(playerArray.length-1)而不是我<(playerArray.length)。 Since your asking for less than and not less than or equal too, it's not gonna return true so replace i < (playerArray.length - 1) with i < (playerArray.length)
由于您也要求小于等于或不小于等于,因此不会返回true,因此将i <(playerArray.length-1)替换为i <(playerArray.length)
You don't need a loop at all if I am understanding the question correctly. 如果我正确理解了这个问题,则根本不需要循环。 You can simply check the length
您可以简单地检查长度
var hasEnoughPlayers = function(playerArray){
return playerArray.length >= 7
}
Here is a full working example... 这是一个完整的工作示例...
var hasEnoughPlayers = function(playerArray){ return playerArray.length === 7; }; var team = [ "Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry Potter" ]; alert(hasEnoughPlayers(team));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.