簡體   English   中英

javascript:使用let vs none確定范圍

[英]javascript: scoping with let vs none

我有一個forEach循環和一個嵌套在其中的for循環。 為什么它在for循環之外,但仍然在forEach循環中,我有word = foo 那么word值可以記錄在整個forEach循環之外,但是,當我讓它let word = "foo" ,控制台日志語句失敗並說word is not defined

function mainFunction() {
    array.forEach(function (element, index) {
       for (var key in list) {
         //do something
       }
       word = "foo"
    }

    console.log(word)
}

如果不使用letvarconst來定義變量,那么JavaScript會隱式地將您的word變量添加到全局對象中。

基本上,這個:

word = "foo"

與此相同:

window.word = "foo"

這被普遍認為是不好的做法,通常表明存在錯誤。 這就是為什么大多數短號都會將此標記為錯誤

讓我們說道

let語句聲明一個塊作用域局部變量,可選擇將其初始化為一個值。

 function test(){ let x = 1; if(x === 1) { let x = 2; console.log(x);// output: 2 } console.log(x); //output: 1 } test(); console.log(x); // Uncaught ReferenceError 

沒有聲明

應使用letconstvar聲明變量。 忽略它們被普遍認為是一個錯誤,因為變量在全球范圍內結束 ,產生全局范圍污染 ,並且難以跟蹤或調試。

它也可能導致變量覆蓋(錯誤,意外行為......)

如果您的代碼以"strict mode" (或模塊內部)運行,則會觸發錯誤。

 function test(){ x = 1; // becomes window.x if(x === 1) { let x = 2; console.log(x);// output: 2 } console.log(x); //output: 1 } test(); console.log(x); // output: 1 console.log(window.x); // output: 1 


解決您的問題

您應該在函數頂部聲明變量。

 function mainFunction(array) { let word; // declare 'word' here array.forEach(function (element, index) { word = "foo"; }) console.log(word) } mainFunction([1,2,3,4]) 

javascript中只有兩個范圍:全局和本地。 唯一可以創建范圍的是function關鍵字

通過首先查看本地范圍來獲取變量,如果未找到,則在鏈上方的父范圍中搜索變量,直到找到為止。 如果未找到並且未設置use strict模式,則會在全局范圍內為您auto創建它們。

隨着中說,你可以看到會發生什么是變量word就是不能在范圍中發現forEach 在這種情況下,JS做了許多人不希望它做的事情以及許多人使用use strict模式的原因...它會在全局范圍內為你添加它,因為它無法位於范圍鏈中的任何位置。

這導致了許多問題,並不是許多人想要的行為。 要停止,你可以添加use strict來告訴JS處於嚴格模式

 'use strict'; var v = "Hi! I'm a strict mode script!"; // this is ok b = 1 // ReferenceError: b is not defined" 

這是相同的,沒有use strict

var v = "Hi! I'm a NOT strict mode script!"; // this is ok
b = 1 
console.log(b) // returns 1
function mainFunction() {
array.forEach(function (element, index) {
   for (var key in list) {
     //do something
   }
   let word = "foo"
   //word is defined here.
   //word can call in {array.forEarch(...)}

}
//word is undefined here.

console.log(word)

}

永遠let叫{...}。 例如: { let a; ... {let b;} {let c;} } { let a; ... {let b;} {let c;} }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM