我正在学习Javascript,for循环,并尝试将两个不同数组中的相同元素放到另一个新数组中。当我将'console.log()‘放在For循环的外部时,它将打印两个公共元素,但是,如果我在if语句中放入’返回console.log()‘,它将不能正常工作(它只显示'Ray’)。
我想知道他们之间的区别。
我会给你留两个密码。非常感谢你的帮助。
//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' ]发布于 2019-11-06 13:49:19
return关键字中断当前函数的执行并返回值。如果在循环中使用它,它一执行就会破坏它。这基本上是直接原因。
更多说明:如果您执行return console.log(mutualFollowers);,那么首先对console.log()进行计算,并将其结果传递给从当前函数返回它的return。console.log()的结果是undefined,所以主函数也将返回undefined。
https://stackoverflow.com/questions/58731582
复制相似问题