![](/img/trans.png)
[英]In ES6 JavaScript, we can use `let` in a for-loop but not in a while-loop?
[英]ES6: Multiple let assignment inside for-loop in 'strict mode'
我正在嘗試“嚴格模式”並在這樣的 for 循環中使用關鍵字 let :
(function() {
"use strict";
var numbers = [1,2,3,4,5];
var value;
for (let i = j = 0; i < numbers.length; i++) {
j += numbers[i];
value = j;
}
console.log ("\tThe reduced value is: ", value);
})();
這會產生一個 Uncaught ReferenceError: j is not defined,但是通過刪除 'use strict' 代碼運行良好。
代碼是我的jsfiddle 的簡化子集
如您所料,問題出在for循環中的Initialiser語句:
let i = j = 0;
該語句等同於:
let i = (j=0);
與以下內容相同:
j = 0; // would throw : Uncaught ReferenceError: j is not defined
let i = j;
如果要修復嚴格模式錯誤,則需要顯式地將j聲明為let j = 0的變量;
由於提升,它在草率模式下工作,這將在全局范圍內創建變量j。 ( https://www.w3schools.com/js/js_hoisting.asp )
編輯:Bergi是正確的,我混淆了一些概念,由於范圍鏈而不是提升范圍,它在全局范圍內可用。 如果未在局部范圍內聲明變量,則它將在該變量的外部詞匯范圍內查看。 如果仍未在此處定義,它將一直沿作用域鏈向上移動,直到達到全局作用域為止。 如果仍未在其中定義它,則它會自動在全局范圍內定義,這是您每次使用j時引用的變量。
那個工程
let i = j = 0
實際上與關鍵字let
無關。 然而
讓我們看一下它的功能:
let i // declares i
j = 0 // assigns a variable j to 0 that is not declared
// If it does not exist it creates the variable on the `window` object.
i = j // in fact i = window.j
正確使用
let i = 0, j = 0
在JavaScript中,如果兩個或多個具有相同優先級的運算符出現在表達式中,則關聯性規則將起作用。
更多信息: 運算符優先級和關聯性
=
具有從右到左的關聯性 。 所以當嘗試評估
let i = j = 0;
,JavaScript實際上首先嘗試執行:
j = 0; // Throws Uncaught ReferenceError: j is not defined in strict mode
但是,通過在全局上下文中創建j
忽略此模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.