首页 > 解决方案 > arr 未在 Javascript 数组中定义

问题描述

以下代码应该计算正面与反面的数量。下面的代码是给我的,但我的任务是计算正面与反面,我尝试了函数 countHeadsAndTails(flips) 及以下,但遇到了一个小问题。我在给我一个错误的行上加上了三个星号:arr 没有定义(在函数 countHeadsAndTails(flips) 下)但在过去的 30 分钟里,我一直在努力解决这个问题,谢谢 :)

var NUM_FLIPS = 100;

var headCount = 0, tailCount = 0;

function start(){
    var flips = flipCoins();
    printArray(flips);
}

// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
    var flips = [];
    for(var i = 0; i < NUM_FLIPS; i++){
        if(Randomizer.nextBoolean()){
            flips.push("Heads");
        }else{
            flips.push("Tails");
        }
    }
    return flips;
}

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        println(i + ": " + arr[i]);
    }
    countHeadsAndTails();
}
function countHeadsAndTails(flips) {
    for (var i = 0; i < NUM_FLIPS; i++) {
    ***if (arr["flips"] === "heads")***
        headCount += arr[i];
    else
        tailCount += arr[i];
}
print("Heads: " + headCount + " " + "Tails: " + tailCount);
}

标签: javascriptarrays

解决方案


您尚未将arr数组声明为全局数组,因此您必须将其传递给应该使用它的函数。该arr数组实际上是flips. 我更改了下面的代码以将数组传递给countHeadsAndTails()函数,并为同一函数添加了一些其他小的更改(请参见下面的箭头)。

运行和测试:

var NUM_FLIPS = 100;

var headCount = 0, tailCount = 0;

function start(){
    var flips = flipCoins();
    printArray(flips);
}

// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
    var flips = [];
    for(var i = 0; i < NUM_FLIPS; i++){
        if( Math.round(Math.random()) ){  //  <- To mimic Randomizer 
            flips.push("Heads");
        } else {
            flips.push("Tails");
        }
    }
    return flips;
}

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        console.log(i + ": " + arr[i]);
    }
    countHeadsAndTails(arr);             //  <- passing array to function 
}

function countHeadsAndTails(flips) {     //  <- array is now called flips again
  for (var i = 0; i < NUM_FLIPS; i++) {
    if (flips[i] === "Heads")            //  <- check the ith element, and capital H
        headCount++;                     //  <- increment headCount
    else
        tailCount++;                     //  <- increment tailCount
  }
  console.log("Heads: " + headCount + " " + "Tails: " + tailCount);
}

start();

注意:为了与正确的 JavaScript 输出语法保持一致,我也更改了print()and 。println()console.log()


推荐阅读