首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >同时循环。无法对while语句进行硬编码

同时循环。无法对while语句进行硬编码
EN

Stack Overflow用户
提问于 2017-05-08 10:42:39
回答 2查看 69关注 0票数 1
代码语言:javascript
运行
复制
function start() {
    var output = "";
    var index = 0;
    var total = 0;
    var average = 0;
    var arr = []
while(arr.length < 12){
    var randomnumber = Math.ceil(Math.random()*20)
    if(arr.indexOf(randomnumber) > -1) continue;
    arr[arr.length] = randomnumber;
}

    output = output + "List of all values in the array: " + arr;
    output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";

while(index < arr.length) {
    total = total + arr[index];
    index++;
    }
    average = total / index;
    output = output + "Total of all values: " + total + "<br/>";
    output = output + "Average of all values: " + average;

document.getElementById("msg").innerHTML = output;
}

我被告知我不被允许硬编码的陈述,我如何去改变'while‘语句,所以我没有硬编码?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-08 10:47:05

可能他们是说

代码语言:javascript
运行
复制
var arr =  new Array(12);
var randIndex=0;

    while(randIndex < arr.length){
        var randomnumber = Math.ceil(Math.random()*20)
        if(arr.indexOf(randomnumber) > -1) continue;
        arr[randIndex] = randomnumber;
        randIndex++;
    }
票数 0
EN

Stack Overflow用户

发布于 2017-05-09 06:55:14

看上去像是学校作业。如果不应该硬编码数组中的元素数(当前为12),则需要从用户那里以某种方式获得该编号。或者使用随机数,如下所示。

注意:如果让用户指定元素的数量,就会有一个陷阱。我会留着它让你去探索和修复。

代码语言:javascript
运行
复制
function start(len) {
    var output = "";
    var index = 0;
    var total = 0;
    var average = 0;
    var arr = []
while(arr.length < len){
    var randomnumber = Math.ceil(Math.random()*20)
    if(arr.indexOf(randomnumber) > -1) continue;
    arr[arr.length] = randomnumber;
}

    output = output + "List of all values in the array: " + arr;
    output = output + "<br/>" + "Total number of values in the array: " + arr.length + "<br/>";

while(index < arr.length) {
    total = total + arr[index];
    index++;
    }
    average = total / index;
    output = output + "Total of all values: " + total + "<br/>";
    output = output + "Average of all values: " + average;

document.getElementById("msg").innerHTML = output;
}

// start(10); // you can get the number of elements in array from user and pass it here. I'm passing hardcoded 10 for now.

start(Math.ceil(Math.random()*20)); // alternatively passing a random number 
代码语言:javascript
运行
复制
<div id='msg'>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43845596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档