我正在学习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。
发布于 2019-11-06 13:49:08
当然了..。return语句停止执行您所处的函数,这意味着它还会中断您所在的for循环。
在您的例子中,只有在找到第一个相互跟随者(即Ray)之后,它才会到达Ray,因此它破坏了函数,只打印了['ray']。
顺便说一句,因为您的返回是在console.log()上,所以它实际上返回了函数之外-- console.log()操作的结果,这是未定义的。
发布于 2019-11-06 13:49:36
关键字return在javascript中退出当前函数,但不只是退出。大多数编程语言都是这样工作的。
因此,当它处理“Ray”时,它退出函数而不处理下一个函数。
https://stackoverflow.com/questions/58731582
复制相似问题