javascript - 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);
}
解决方案
您尚未将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()
推荐阅读
- javascript - 无法删除数字上的逗号(JS、HTML)
- javascript - javascript返回多个带有.join()的字符串---字符串[i].join(“”)不起作用
- c++ - 如何在主函数中访问订阅者类的公共变量?
- mysql - 构建一个 laravel 子查询
- java - Android Studio 在 generateJava 文件夹中生成 AIDL java 文件,包名错误
- css - 悬停时更改 div 中的 img(最后一个/第一个孩子)
- opayo - 3DSv2 Sagepay 直接集成基础知识
- javascript - React/Redux URL 不匹配:当数组项编号与对象 id 不同时
- azure-application-insights - 不会为 AppInsights webTest 触发指标警报
- elasticsearch - 更新所有文档字段条目