简体   繁体   中英

IF ELSE condition is always going to the ELSE

Here is my POST request:

router.post('/', (req, res) => {
    let body = { ...req.body };
    let odd = new Array();
    let even = new Array();
    let is_success = true;

    body.array.forEach((element) => {
        if (Number.isInteger(element)) {
            if (element % 2 == 0) {
                even.push(element);
            } else {
                odd.push(element);
            }
        } else {
            is_success = false;
            return;
        }
    });
    if (is_success) {
        res.status(200).json({
            is_success: `${is_success}`,
            user_id: 'john_doe_17091999',
            odd: `${odd}`,
            even: `${even}`,
        });
    } else
        res.status(200).json({
            is_success: `${is_success}`,
            user_id: 'john_doe_17091999',
        });
});

The condition is_success is not becoming true and that takes it to the else condition always. What I am trying to do is take the array and return odd and even arrays if all input elements are Integers:

{
"array": ["1", "2", "3"] 
}

Response:

{
"successful": true,
"odd": [1, 3],
"even": [2],
}

What it is always responding with:

{
    "is_success": "false",
    "user_id": "john_doe_17091999"
}

Your array contains strings. You need to convert them to numbers before you can run Number.isInteger() on them, otherwise it will always return 'false'. You can do that by putting a '+' before the element. See below.

Number.isInteger(+element)

You must cast every element to Number before using the Number.isInteger otherwise you'll get false.

Example: Number.isInteger("2") will return false Number.isInteger(Number("2")) will return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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