简体   繁体   English

偶 奇 javascript 浏览数组

[英]Even Odd javascript browse an array

how to browse an array to find out if all the numbers in the array are even or odd?如何浏览数组以找出数组中的所有数字是偶数还是奇数?

thanks you.感谢您。

script脚本

 function evenOdd() {
    let tab = [10, 5, 8, 1];
    if (tab % (2 = 0)) {
        console.log('even');
    } else {
        console.log('odd');
    }
}
console.log(evenOdd());

You need to iterate the values from the array and check the value with the comparison operator === instead of an assignment = .您需要迭代数组中的值并使用比较运算符===而不是赋值=检查值。

 function evenOdd() { let tab = [10, 5, 8, 1]; for (const value of tab) { if (value % 2 === 0) { console.log(value, 'even'); } else { console.log(value, 'odd'); } } } evenOdd(); // no console.log because no return value

The trick is to assume, that your list only contains even numbers until an odd number is encountered and that it only contains odd numbers until an even number is encountered诀窍是假设您的列表只包含偶数,直到遇到奇数,并且它只包含奇数,直到遇到偶数

 function evenOdd(tab) { let isEven = true; let isOdd = true; for (let value of tab) { // note: no comparision to 0 or 1 needed, as value % 2 is already // truthy for odd value and falsy for even value if (value % 2) { isEven = false; } else { isOdd = false; } } return {isEven, isOdd}; } let tab = [10, 5, 8, 1]; let {isEven, isOdd} = evenOdd(tab);

You will also need to return two distinct booleans or an integer, as there are 3 different return options: all even, all odd, or even and odd mixed.您还需要返回两个不同的布尔值或 integer,因为有 3 种不同的返回选项:全偶数、全奇数或偶数和奇数混合。

First, I would call the function outside of a console.log().首先,我会在 console.log() 之外调用 function。 This is because you already are consoling the result in the if statement and there is no return value.这是因为您已经在 if 语句中安慰结果并且没有返回值。

Second, you need to make sure that you are using some method to map over the array.其次,您需要确保您正在使用某种方法来 map 超过阵列。 In this case, I would use a.forEach().在这种情况下,我会使用 a.forEach()。

Last, you want to check it the item divided by 2 equals 0. To do this it looks like:最后,您要检查项目除以 2 是否等于 0。为此,它看起来像:

item % 2 === 0

For the final result I would do this:对于最终结果,我会这样做:

function evenOdd() {
    let tab = [10, 5, 8, 1]

    tab.forEach((item) => {
        item % 2 === 0
            ? console.log(item, "even")
            : console.log(item, "odd")
    })
}

evenOdd()

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

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