为什么我的for循环只返回一次值?

时间:2016-04-05 12:42:01

标签: javascript for-loop

function getValue () {
   console.log(1);
   return 2;
};

for (let  i = 0; i < 1000; i++) {   
   getValue();
}

它将打印1千次,但在这里它将在循环结束时返回两次。为什么呢?

2 个答案:

答案 0 :(得分:1)

它没有被运行过一次。你最有可能看到的是:

enter image description here

参见&#34; 1000&#34;?这意味着&#34; 1&#34;输出了1000次。你的javascript控制台只是试图为你节省一些空间。如果您每次看到该消息的唯一实例时将数字更改为不同的数字:

enter image description here

如果您的问题是&#34;为什么会说&#39; 1&#39; 1000次,但只有&#39; 2&#39;一次性#34;那么答案很简单。您只执行该功能但从不打印其返回值,因此您会看到 last 返回值。如果您还要打印2,请使用console.log( getValue() );

&#34;为什么我会想要最后一次通话的结果???&#34;

因为这样的东西太棒了:

enter image description here

答案 1 :(得分:0)

也许我已经明白了你的意思......

你看到的是1000的1,而不是2,你想知道为什么你只看到一个2?

你的函数实际上会返回2次1000次,但是你的代码没有做任何事情,它会丢失&#34;并且控制台会输出你最后一个可用的返回值,即getValue的第1000个功能

如果你在循环后添加一个新的返回,你将看不到2,你会看到这个新的返回值,如下所示:

function getValue () {
   console.log(1);
   return 2;
};

for (let  i = 0; i < 1000; i++) {   
   getValue();
};
var x=function(){
    return "return value string, that you see only once in the console"}
x();
x();

如您所见,我们调用x()函数两次,但我们只在控制台中看到返回的字符串一次。

相关问题