3 回答

TA贡献1836条经验 获得超5个赞
正如其他人指出的那样,该return行正在中断for ...循环并返回始发调用。如果确实需要从函数重复返回,则可以尝试使用回调函数来处理每个交互。
function addTwo(num){
return num + 2;
}
function checkConsistentOutput(func, val, callback){
let first = func(val);
let second = func(val);
if(first === second){
for(let i = 0; i < 5; i++){
if ( typeof callback === "function" ){
callback(first);
}
}
}else{
console.log("This function returned inconsistent results");
}
}
checkConsistentOutput(addTwo, 2, function(res){
console.log("Result: " + res);
} );

TA贡献1859条经验 获得超6个赞
实际的问题是,当您使用returninfor循环时,它会立即从循环中返回,如果您需要使用45次console.log()或可以使用一个计数器来计数发生的次数4,然后可以从该计数器中要求条件是通过还是失败
现在,您可以看一下代码片段,并查看console.log的工作方式
function addTwo(num){
return num + 2;
}
//Is addTwo stable?
function checkConsistentOutput(func, val){
let first = func(val);
let second = func(val);
if(first === second){
for(let i = 0; i < 5; i++){
console.log(first);
}
}else{
console.log("This function returned inconsistent results");
}
}
checkConsistentOutput(addTwo, 2);
添加回答
举报