繁体   English   中英

如何使用数组作为参数的innerHTML函数?

[英]How to innerHTML a function with array as parameter?

我正在学习循环使用thorugh数组-我想使用innerHTML将forEach函数(在另一个函数中,以数组为参数)的if else语句的结果传递给使用innerHTML的HTML(如果您知道更好的方法,则不必是innerHTML没关系)。 它检查数字是否为偶数,并应返回true和false。 我的结果是不确定的,但是在console.log中我可以看到循环正在工作。 我不知道如何正确选择它,在底部留下了“这里有什么”。

欢迎提供任何帮助,包括重建代码。

var myArray = function (nums) {

    var average = 0;
    var totalSum = 0;

    nums.forEach(function (value) {
        //returns total sum
        totalSum = totalSum + value;

        //return average
        average = totalSum / nums.length;

        //return true if at least one even if not false
        if (value % 2 === 0) {
            console.log(value + " true");
            return true;
        } else {
            console.log(value + " false");
            return false;
        };

    })

    console.log("Total sum: " + totalSum);
    console.log("Average: " + average);
    console.log("Max number: " + Math.max.apply(null, nums));
    //document.getElementById("array").innerHTML = /*What in here?!*/
};


myArray([1, 1, 1, 2])

只需为偶数或奇数的出现取一个变量即可。

var myArray = function (nums) {
    var average = 0;
    var totalSum = 0;
    var hasEven = false; // flag if at least one value is even => true, otherwise false
    nums.forEach(function (value) {
        totalSum = totalSum + value;
        hasEven = hasEven || !(value % 2);
    });
    average = totalSum / nums.length; // just call it once
    console.log("Total sum: " + totalSum);
    console.log("Average: " + average);
    console.log("Max number: " + Math.max.apply(null, nums));
    console.log("Contains at least one even value: " + hasEven);
};
myArray([1, 1, 1, 2]);

一种简单的方法是使用JSON.Stringify

document.getElementById("array").innerHTML = JSON.Stringify(nums);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM