简体   繁体   中英

JS console.log method prints value twice

I have the following code which seems to work basically fine.

The purpose of the code is to print all names starting with an S (case sensitive), to console.

let names = ['Selma', 'Yirma'];
let sNames = [];
names.forEach( (e)=>{
    if (e.charAt(0) === 'S') {
        sNames.push(e);
    }
        console.log(sNames);
});

I used the code in Google chrome console but got "Selma" twice. Why is that? Why not just once?

You are seeing Selma twice because in the first iteration of the loop you push it to sNames, then you log sNames, then you log it again on Yirma. So you see Selma twice. Move your console.log outside of the loop.

let names = ['Selma', 'Yirma'];
let sNames = [];
names.forEach( (e)=>{
    if (e.charAt(0) === 'S') {
        sNames.push(e);
    }
});
console.log(sNames);

Because your console.log() is inside in for loop, Move console.log() outside of the loop.

  let names = ['Selma', 'Yirma']; let sNames = []; names.forEach( (e)=>{ if (e.charAt(0) === 'S') { sNames.push(e); } }); console.log(sNames); 

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