JavaScript - 代码工作 - 但不理解逻辑



VS代码+终端

代码如下:

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);

***为了清楚起见,代码是有效的。然后,双方共享的名称将成功记录到控制台。这是CodeAcademy的一项任务。然而,我理解除了最后一步之外的所有步骤,其中:;mutualFollowers.prush([bobsFollowers[i]])"——为什么";bobsFollowers[i]";现在指的是bobsFollowers和tinasFollowers共享的元素?

我很难理解其中的逻辑。如果有人能向我解释这一点,我将不胜感激。希望这有意义:)

由于前面的条件if (bobsFollowers[i] === tinasFollowers[j])我们可以假设它们在各自的索引处共享相同的跟随器,所以在这种情况下,代码只是将bobsFollowers[i]添加到mutualFollowers数组中。如果代码使用了tinasFollowers[j].:)希望能有所帮助!

最新更新