亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

學習ES6時let用于for循環時,函數里console的問題

學習ES6時let用于for循環時,函數里console的問題

GCT1015 2018-09-11 12:32:17
 var a = [];    for (let i = 0; i < 10; i++) {       a[i] = function () {        console.log(i);       };     }     a[6](); //6     console.log(a[6]); //  function(){console.log(i)}既然循環結束后,數組a的每一項都是function(){console.log(i)},那么a[6]()輸出是6是怎么實現的?難道let保存了10個狀態?
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

> console.log(i);  //10ReferenceError: i is not defined

let是塊作用域聲明,出了for循環就失效了~


a[6](); //6
for (let i = 0; i < 10; i++) {
  a[i] = function () {    console.log(i);
  };
}

在匿名函數作用域中log(i)引用了上層作用域的變量 i,構成閉包。
a[i]中保存了10個閉包,各自保留了構成閉包時變量 i的值。


2個閉包栗子~

> var f=function(){

...  let i=0;

...  return function(){

.....  i=i+1

.....  return i

.....  }}()

undefined

> f()

1

> f()

2

> f()

3

> f()

4

> f()

5

> var fn;

undefined

> for(let i=-1;i<0;i++){

...     fn=function(){

.....         i=i+1

.....         return i

.....     }

... }

[Function]

> fn()

0

> fn()

1

> fn()

2

> fn()

3

>


查看完整回答
反對 回復 2018-10-29
  • 1 回答
  • 0 關注
  • 629 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號