猿问

为什么我不能多次返回值-就像在for循环中一样?

运行此代码段时,将获得“ 4”作为输出,但是我想将值“ 4”返回5次。


为什么会这样,我该如何解决?


function addTwo(num){

  return num + 2;

}


function checkConsistentOutput(func, val){

  let first = func(val);

  let second = func(val);

  if(first === second){

    for(let i = 0; i < 5; i++){

    return first;

    }

  }else{

    console.log("This function returned inconsistent results");

  }

}


console.log(checkConsistentOutput(addTwo, 2));


ITMISS
浏览 196回答 3
3回答

一只甜甜圈

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

慕丝7291255

实际的问题是,当您使用returninfor循环时,它会立即从循环中返回,如果您需要使用45次console.log()或可以使用一个计数器来计数发生的次数4,然后可以从该计数器中要求条件是通过还是失败现在,您可以看一下代码片段,并查看console.log的工作方式function addTwo(num){&nbsp; return num + 2;}//Is addTwo stable?function checkConsistentOutput(func, val){&nbsp; let first = func(val);&nbsp; let second = func(val);&nbsp; if(first === second){&nbsp; &nbsp; for(let i = 0; i < 5; i++){&nbsp; &nbsp; console.log(first);&nbsp; &nbsp; }&nbsp; }else{&nbsp; &nbsp; console.log("This function returned inconsistent results");&nbsp; }}checkConsistentOutput(addTwo, 2);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答