javascript - 数组 数学逻辑 JavaScript

标签 javascript arrays math logic

我似乎无法列出数组中偶数的数量,而且当我将数组整数乘以乘数时也无法得到结果。我已经想了很长时间了,我无法再思考了。提前致谢!

<!DOCTYPE HTML>
<html>

<head>
<meta charset="utf-8">
<title>EvensMultiply</title>
<script type="text/javascript">
    /*Write a defining table and a function named countEvens that counts and returns the number of even integers in an array. The function must have this header: function countEvens(list)*/

    // This function will call and test countEvens() and multiply(list, multiplier).
    function testFunctions() {
        var list = [17, 8, 9, 5, 20];
        var multiplier = 3;
        var result1 = 0;
        var result2 = 0;
        var result3 = 0;
        result1 = countEvens(list);
        //result2 = multiply(list, multiplier);
        result3 = "These are the even numbers of the array list: " + result1 + "<br>" + "This is the array list multiplied by 3: " + result2;
        document.getElementById("outputDiv").innerHTML = result3;
    }
    // This function will find the even intergers in the array.
    function countEvens(list) {
        var evens = [];
        for (var i = 0; i < list.length; ++i) {
            if ((list[i] % 2) === 0) {
                evens.push(list[i]);
                return evens;
            }
        }

    }
    /*Write a defining table and a function to multiply each element in an array by some value. The function must have this header: function multiply(list, multiplier)*/

    // This function will multiply the array list by a multiplier.
    function multiply(list, multiplier) {
        var products;
            products=list.map(function(list){return list * multiplier;});
        return products;
    }
 </script>
 </head>
 <h1>Find evens and multiply by multiplier.</h1>
 <h2>Array list [17, 8, 9, 5, 20]</h2>
 <h3>Click the Compute button to test.</h3>
 <button type="button" onclick="testFunctions()">Compute</button>
 <div id="outputDiv"></div>

 </html>

最佳答案

循环完成后需要返回:

// This function will find the even intergers in the array.
function countEvens(list) {
    var evens = [];
    for (var i = 0; i < list.length; ++i) {
        if ((list[i] % 2) === 0) {
            evens.push(list[i]);
        }
    }
    return evens;
}

关于javascript - 数组 数学逻辑 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191397/

相关文章:

javascript - 从 console.table() 中删除索引

javascript - Safari 不像其他浏览器那样对对象数组进行排序

ruby-on-rails - Ruby:根据 block 查找条件删除并返回数组值

Java Math.cos(Math.toRadians(<angle>)) 返回奇怪的值

iphone - 增强现实方位/航向/方位角困惑。 (iPhone ARKit 代码)

c - Project Euler Number 160 - C 语言尝试

javascript - 计算距每个树节点的水平距离

javascript - JQPLOT条形图范围

javascript - 子组件在 Angular 4 中不起作用

javascript - 如何制作多个嵌套对象的数组?