简体   繁体   中英

JavaScript - Code Working - But Don't Understand Logic

VS CODE + TERMINAL

The code is as follows:

const bobsFollowers = ['John', 'Dan', 'Matt', 'Ted'];

const tinasFollowers = ['Sarah', 'Dan', 'Ted']; 

const mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
for (let j = 0; j < tinasFollowers.length; j++) {
    if (bobsFollowers[i] === tinasFollowers[j]) { 
        mutualFollowers.push([bobsFollowers[i]])
    }
}
} 

console.log(mutualFollowers);

*** Just to be clear the code is functional. The names which are shared by both are then logged to the console successfully. This is a task taken from CodeAcademy. However, I understand all steps except for the final step where: "mutualFollowers.push([bobsFollowers[i]])" -- why is it that "bobsFollowers[i]" is now referring to the elements which both bobsFollowers and tinasFollowers share?

I'm struggling to understand the logic of this. If anyone could explain this to me it would be greatly appreciated. Hope this makes sense:)

Because of the previous conditional if (bobsFollowers[i] === tinasFollowers[j]) we can assume that they both share the same followers at their respective indexes, so in this case the code just goes with adding bobsFollowers[i] to the mutualFollowers array. The same would have been true if the code had used tinasFollowers[j] . :) Hope that helps!

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