如何在循环外获取循环值 [英] How to get loop value outside the loop

查看:140
本文介绍了如何在循环外获取循环值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在下面的示例循环之外获取循环值仅显示最后一个值,例如,如果我想打印循环结果.

How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.

var result;

    for (var i=0; i < 10; i++) {
          result = i;
    }

    console.log(result);

现在如何在控制台中获取循环的迭代值(1到10),因为现在我只打印最后一个值为10的值.

Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.

推荐答案

将log语句放入设置值的循环内.

Put the log statement inside the loop where you set the value.

var result;

for (var i=0; i < 10; i++) {
    result = i;
    console.log(result);
}

如果只需要一条输出语句,则可以在记录之前将结果连接起来:

If you only want one output statement, you can concatenate your results before logging:

var result = "";

for (var i=0; i < 10; i++) {
    result += i + " ";
}

console.log(result);

这将输出0 1 2 3 4 5 6 7 8 9 10

这篇关于如何在循环外获取循环值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆