dimanche 19 avril 2020

Is it possible to write one way ternary operator?

I would like to replace if statement with the ternary operator. The case in my code is that I would like to use one if statement rather than if-else. But it seems ternary operators take a mandatory else statement.

My intended code that produces error is:

for(let i = 0; i<fibArr.length; i++) {
    !fibArr[i] % 2 === 0 ? result += fibArr[i]; //The problem area
}

Instead, I have to write the code that runs without any problems:

for(let i = 0; i<fibArr.length; i++) {
    if(fibArr[i] % 2 !== 0) {
        result += fibArr[i]
    }
}

Full code:

function sumFibs(num) {
    let a = 0, b = 1, fib = 0; 
    let i = 0; 
    let fibArr = []
    let result = 0; 

    while(fib <= num){
        fibArr.push(fib)
        a = b; 
        b = fib; 
        fib = a+b; 
    }

    for(let i = 0; i<fibArr.length; i++) {
        if(fibArr[i] % 2 !== 0) {
            result += fibArr[i]
        }
    }
    console.log(result)
    return result; 
}

Aucun commentaire:

Enregistrer un commentaire