在 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
Returning values out of for loop in javascript
提问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 return
I 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
回答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;
}