在 javascript 中从 for 循环返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8131838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:48:59  来源:igfitidea点击:

Returning values out of for loop in javascript

javascriptarraysobject

提问by jeffreynolte

I have the following function:

我有以下功能:

  function getId(a){
    var aL = a.length;
    for(i = 0; i < aL; i++ ){
      return a[i][2].split(":", 1)[0];
    }    
  }                          

and when using console.log()within the function instead of returnI get all of the values in the loop, and the same goes for document.write. How can I access these values as a string for use in another section of my code?

console.log()在函数中使用而不是return我得到循环中的所有值时,同样适用于document.write. 如何将这些值作为字符串访问以在我的代码的另一部分中使用?

Thank you in advance.

先感谢您。

采纳答案by Gabi Purcaru

You can do that with yieldin newer versions of js, but that's out of question. Here's what you can do:

你可以yield在较新版本的 js 中做到这一点,但这是不可能的。您可以执行以下操作:

function getId(a){
  var aL = a.length;
  var values = [];
  for(i = 0; i < aL; i++ ){
    values.push(a[i][2].split(":", 1)[0]);
  }    
  return values.join('');
}  

回答by fncomp

You gotta cache the string and return later:

您必须缓存字符串并稍后返回:

function getId(a){
    var aL = a.length;
    var output = '';
    for(var i = 0; i < aL; i++ ){
       output += a[i][2].split(":", 1)[0];
    }    
    return output;
} 

回答by Awesome

  • The return statement breaksthe loop once it is executed. Therefore consider putting the returnstatement outsidethe loop.
  • Since you want to return a string, you will create a variable and assign it to an empty string.(This is where will append/add results from the loop.)
  • return the string variable.
  • return 语句一旦执行就会中断循环。因此考虑将返回声明之外循环
  • 由于您想返回一个字符串,您将创建一个变量并将其分配给一个空字符串。(这是将追加/添加循环结果的地方。)
  • 返回字符串变量。

So final code will look like...

所以最终的代码看起来像......

function getId(a){
    var result = '';
    var aL = a.length;
    for(i = 0; i < aL; i++ ){
      result += a[i][2].split(":", 1)[0];
    } 
    return result;
  }