samedi 2 mai 2020

Return in an if

i was practice a kind of filter with a for and if, but i found an output without sense to me, can anyone clarify me the difference for the outputs? Thanks for your time

function eg1(param) {
    sum=[]
    for (let i = 0; i < param.length; i++) {
        let elements = param[i];
        if (elements>0) {
            return sum.push(elements)
        }
    } 
   return sum.length
}

function eg2(param) {
    sum=[]
    for (let i = 0; i < param.length; i++) {
        let elements = param[i];
        if (elements>0) {
            sum.push(elements)
        // return sum.push(elements)
        }
    } 
   return sum.length
}
console.log(eg1([0,-3,1,5])) // 1
console.log(eg2([0,-3,1,5])) // 2

Aucun commentaire:

Enregistrer un commentaire