计算和比较数组中的元素

时间:2019-07-13 21:01:28

标签: javascript arrays

playerArray有七个元素。如果要传递给hasEnoughPlayers的数组至少为7,我想返回true,否则返回false。

我尝试使用playerArray.length - 1。仍然不起作用。

var hasEnoughPlayers = function(playerArray){
    for (var i = 0; i < (playerArray.length - 1); i++){
        if ((playerArray.length - 1) == 7){
           return false;
        }
        else {
            return true;

        }
    }
};

我不断收到错误消息或某些错误消息。 这是使用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));

2 个答案:

答案 0 :(得分:0)

您正在执行i <(playerArray.length-1)而不是i <(playerArray.length)。由于您也要求小于等于或不小于等于,因此不会返回true,因此将i <(playerArray.length-1)替换为i <(playerArray.length)

答案 1 :(得分:0)

如果我正确理解了这个问题,则根本不需要循环。您可以简单地检查长度

var hasEnoughPlayers = function(playerArray){
    return playerArray.length >= 7
}

这是一个完整的示例...

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));