【发布时间】:2019-11-06 21:49:36
【问题描述】:
我正在研究 Javascript、for 循环,并尝试将相同元素从两个不同的数组放入另一个新数组。 当我将 'console.log()' 放在 For 循环之外时,它将打印两个常见元素,但是,如果我将 'return console.log()' 放在 if 语句中,它将无法正常工作(它只显示 [ '雷']。)
我想知道它们之间的区别。
我会给你留下两个代码。 非常感谢您的帮助。
//code1
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
let 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)//output: [ 'Ray', 'Kay' ]
//code2
let bobsFollowers = ['Natalia', 'Ray', 'Kay', 'Clau'];
let tinasFollowers = ['Ray', 'Yama', 'Kay'];
let 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])
return console.log(mutualFollowers)
}
}
}// output: [ 'Ray' ]
【问题讨论】:
-
也许您对这个问题的更高级解决方案感兴趣:stackoverflow.com/questions/37320296/…