javascript和var之間的區別?

You can define your variables in JavaScript using two keywords - the let keyword and the var keyword. The var keyword is the oldest way of defining and declaring variables in JavaScript whereas the let is fairly new and was introduced by ES15.

您可以使用兩個關鍵字( let關鍵字和var關鍵字) 在JavaScript中定義變量 。 var關鍵字是在JavaScript中定義和聲明變量的最古老的方法,而let是相當新的,是ES15引入的。

In this article, we'll look at the differences between the two so you know when to use which for your variables.

在本文中,我們將研究兩者之間的區別,以便您知道何時將哪個變量用于變量。

Open the chrome dev console to try out the examples by right-clicking on the browser → selecting inspect → selecting console or simply type f12.

通過右鍵單擊瀏覽器→選擇檢查→選擇控制臺,打開chrome dev控制臺以嘗試示例,或者直接鍵入f12。

Example 1:

范例1:

var size=32;
console.log(size);

Output

輸出量

32

Example 2:

范例2:

var size=63;
console.log(size);

Output

輸出量

63

We declared a variable size with a value 32. Then we redeclared it with another value, 63. Everything looks fine till now.

我們聲明了一個可變大小,值為32 。 然后,我們用另一個值63對其進行了重新聲明。 到目前為止一切都很好。

let length=14;
console.log(length);

Output

輸出量

14

let length=14;
let length=20; //will produce error
console.log(length);

Output

輸出量

Uncaught SyntaxError: Identifier 'length' has already been declared
at <anonymous>:1:1

let length=14;
length=20; //no produce error
console.log(length);

Output

輸出量

20

Now we create a length variable with a value 14 but this time using the let keyword. When we redeclare the same variable with another value we get a SyntaxError saying it has already been declared. The first point of difference between let and var is that using var we can redeclare those variables but with let, we can only redefine them, not redeclare them. When we reassign the value 20 to the variable length, we get no error on the console and our length variable happily takes a new value.

現在我們創建一個長度變量,值為14,但是這次使用let關鍵字 。 當我們用另一個值重新聲明相同的變量時,我們得到一個SyntaxError,它已經被聲明。 let和var之間的第一點區別是,使用var可以重新聲明這些變量,但是使用let ,我們只能重新定義它們,而不能重新聲明它們。 當我們將值20重新分配給變量length時 ,在控制臺上沒有錯誤,并且我們的length變量愉快地采用了一個新值。

var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
var ironMan = 'silver';
let captainAmerica = 'golden';
console.log(ironMan);
console.log(captainAmerica);
}

Output

輸出量

silver
Golden

var ironMan = 'red';
var captainAmerica = 'blue';
if (ironMan === 'red') {
var ironMan = 'silver';
let captainAmerica = 'golden';
console.log(ironMan);
console.log(captainAmerica);
}

Output

輸出量

silver
Blue

The next difference between the two is the scope. You can observe from the above code that captainAmerica is declared again inside using the let keyword with a value 'golden' and inside that if block it persists that value, however, outside that if block when we log it's value to the console we get the older value 'blue' which was defined outside the if block. Thus variables declared using the let keyword have block scope. On the other hand, we changed the value of ironMan inside the if block and it continues to hold that value even after the if block is over. We can say that var takes the scope of it's enclosing execution context which can be a function or even the global scope as in this case.

兩者之間的下一個區別是范圍。 您可以從上面的代碼中觀察到,在captainAmerica內部再次使用let關鍵字聲明了“黃金”值,并且在if塊內部將其持久保留該值,但是在if塊之外,當我們將其值記錄到控制臺時,我們得到了在if塊外定義的舊值“ blue” 。 因此,使用let關鍵字聲明的變量具有塊范圍。 另一方面,我們更改了if塊內的ironMan的值, 即使 if塊結束,它仍繼續保持該值。 我們可以說var接受其封閉執行上下文的范圍,在這種情況下,它可以是函數甚至是全局范圍。

Heads up: The reason let was introduced was to avoid using global variables and namespaces everywhere. It's a bad, no wait, terrible programming habit. Avoid using global variables where their global scope renders absurd. Use let wherever possible.

注意:引入let的原因是為了避免在各處使用全局變量和名稱空間。 這是一種不好的,迫不及待的可怕的編程習慣。 避免在全局變量變得荒謬的地方使用全局變量。 盡可能使用let

Finally, the last difference I want to talk about is Hoisting. Consider the following piece of code,

最后,我要談的最后一個區別是吊裝 。 考慮下面的代碼,

x = 5;
console.log(x);
var x;

Output

輸出量

5

If you've worked with languages like C/C++ you might find it strange. In such languages, you can expect an error saying something like x is not defined because compiler reads from top to bottom. So is JS also executed from top to bottom? Well, if it were, you wouldn't be able to do this. Then how come we can use a variable and declare it later? The answer is hoisting. Hoisting means moving all declarations to the top. This means that while executing the code, all variable declarations are on the top so till the time you come to x=5 line you already know that x has been declared a variable somewhere in the program.

如果您使用過C / C ++之類的語言,則可能會覺得很奇怪。 在這樣的語言中,您可能會遇到一個錯誤,即未定義類似x的內容,因為編譯器從上到下讀取。 JS也是從頭到尾執行嗎? 好吧,如果是這樣,您將無法做到這一點。 那么我們如何使用變量并在以后聲明它呢? 答案正在提升。 吊裝意味著將所有聲明移到頂部。 這意味著在執行代碼時,所有變量聲明都位于頂部,因此直到您到達x = 5行時,您已經知道x已在程序中的某個位置聲明為變量。

y = 3;
function setRandom(y) {
console.log('Before declaring y: ', y);
}
setRandom();
var y;
console.log('After declaring y: ', y);

Output

輸出量

Before declaring y:  undefined
After declaring y:  3

Let's try to hoist a variable using let,

讓我們嘗試使用let提升變量,

x = 5;
console.log(x);
let x;

Output

輸出量

VM2466:1 Uncaught ReferenceError: Cannot access 'x' before initialization
at <anonymous>:1:2

We get an error saying we can't access it before it is even initialized. So are variables declared with the let keyword not hoisted? They are, but they're hoisted in a temporal dead zone. A zone where you can use variables that have not been defined yet.

我們收到一條錯誤消息,說我們甚至無法在初始化之前訪問它。 那么,沒有懸掛用let關鍵字聲明的變量嗎? 它們是,但是它們被吊在一個臨時的死區中。 您可以在其中使用尚未定義的變量的區域。

Note: if you are using strict mode in your JavaScript then you're more likely to run into getting undefined values for such types of code because strict mode does not allow any hoisting to take place.

注意:如果您在JavaScript中使用嚴格模式,那么您很可能會遇到此類代碼的未定義值,因為嚴格模式不允許任何提升。

So is hoisting in TDZ useless? Well not really, consider the following example using an asynchronous function.

那么在TDZ中吊起是沒有用的嗎? 并非如此,請考慮以下使用異步函數的示例。

for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}

Output

輸出量

3

Out setTimeout is an asynchronous function and after 1 sec it prints the value of i which was incremented 4 times while that asynchronous function was running. However if we use let instead of var,

setTimeout輸出是一個異步函數,在1秒鐘后它將打印i的值,該值在該異步函數運行時增加了4倍。 但是,如果我們使用let而不是var

for (let i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, 1000)
}

Output

輸出量

0
1
2

Now we get all the values that i took during that loop traversal. This is because of the TDZ or the temporal dead zone where let is hoisted. Thus using async can help you retain your values through TDZ hoisting if you use let instead of var. Remember to clean your code by replacing all var with let and make it a good practice to use block scopes instead of global scopes!

現在,我們所有的值, 我該循環遍歷期間舉行。 這是因為TDZ或懸掛了let 的時間盲區 。 因此,如果使用let而不是var,則使用async可以幫助您通過TDZ提升保留值。 請記住通過用let替換所有var來清理代碼,并使其成為使用塊范圍而不是全局范圍的好習慣!

翻譯自: https://www.includehelp.com/code-snippets/var-vs-let-in-javascript.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/378273.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/378273.shtml
英文地址,請注明出處:http://en.pswp.cn/news/378273.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

小米手環6NFC安裝太空人表盤

以前看我室友峰哥、班長都有手環&#xff0c;一直想買個手環&#xff0c;不舍得&#xff0c;然后今年除夕的時候降價&#xff0c;一狠心&#xff0c;入手了&#xff0c;配上除夕的打年獸活動還有看春晚京東敲鼓領的紅包和這幾年攢下來的京東豆豆&#xff0c;原價279的小米手環6…

計算機二級c語言題庫縮印,計算機二級C語言上機題庫(可縮印做考試小抄資料)...

小抄,答案,形成性考核冊,形成性考核冊答案,參考答案,小抄資料,考試資料,考試筆記第一套1.程序填空程序通過定義學生結構體數組&#xff0c;存儲了若干個學生的學號、姓名和三門課的成績。函數fun 的功能是將存放學生數據的結構體數組&#xff0c;按照姓名的字典序(從小到大排序…

為什么兩層3*3卷積核效果比1層5*5卷積核效果要好?

目錄1、感受野2、2層3 * 3卷積與1層5 * 5卷積3、2層3 * 3卷積與1層5 * 5卷積的計算量比較4、2層3 * 3卷積與1層5 * 5卷積的非線性比較5、2層3 * 3卷積與1層5 * 5卷積的參數量比較1、感受野 感受野&#xff1a;卷積神經網絡各輸出特征像素點&#xff0c;在原始圖片映射區域大小。…

算法正確性和復雜度分析

算法正確性——循環不變式 算法復雜度的計算 方法一 代換法 —局部代換 這里直接對n變量進行代換 —替換成對數或者指數的情形 n 2^m —整體代換 這里直接對遞推項進行代換 —替換成內部遞推下標的形式 T(2^n) S(n) 方法二 遞歸樹法 —用實例說明 —分析每一層的內容 —除了…

第十五章 Python和Web

第十五章 Python和Web 本章討論Python Web編程的一些方面。 三個重要的主題&#xff1a;屏幕抓取、CGI和mod_python。 屏幕抓取 屏幕抓取是通過程序下載網頁并從中提取信息的過程。 下載數據并對其進行分析。 從Python Job Board&#xff08;http://python.org/jobs&#x…

array_chunk_PHP array_chunk()函數與示例

array_chunkPHP array_chunk()函數 (PHP array_chunk() Function) array_chunk() function is an array function, it is used to split a given array in number of array (chunks of arrays). array_chunk()函數是一個數組函數&#xff0c;用于將給定數組拆分為多個數組(數組…

raise

raise - Change a windows position in the stacking order button .b -text "Hi there!"pack [frame .f -background blue]pack [label .f.l1 -text "This is above"]pack .b -in .fpack [label .f.l2 -text "This is below"]raise .b轉載于:ht…

c語言輸出最大素數,for語句計算輸出10000以內最大素數怎么搞最簡單??各位大神們...

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓#include #include int* pt NULL; // primes_tableint pt_size 0; // primes_table 數量大小int init_primes_table(void){FILE* pFile;pFile fopen("primes_table.bin", "rb");if (pFile NULL) {fputs(&q…

【數據結構基礎筆記】【圖】

代碼參考《妙趣橫生的算法.C語言實現》 文章目錄前言1、圖的概念2、圖的存儲形式1、鄰接矩陣&#xff1a;2、鄰接表3、代碼定義鄰接表3、圖的創建4、深度優先搜索DFS5、廣度優先搜索BFS6、實例分析前言 本章總結&#xff1a;圖的概念、圖的存儲形式、鄰接表定義、圖的創建、圖…

第十六章 測試基礎

第十六章 測試基礎 在編譯型語言中&#xff0c;需要不斷重復編輯、編譯、運行的循環。 在Python中&#xff0c;不存在編譯階段&#xff0c;只有編輯和運行階段。測試就是運行程序。 先測試再編碼 極限編程先鋒引入了“測試一點點&#xff0c;再編寫一點點代碼”的理念。 換而…

如何蹭網

引言蹭網&#xff0c;在普通人的眼里&#xff0c;是一種很高深的技術活&#xff0c;總覺得肯定很難&#xff0c;肯定很難搞。還沒開始學&#xff0c;就已經敗給了自己的心里&#xff0c;其實&#xff0c;蹭網太過于簡單。我可以毫不夸張的說&#xff0c;只要你會windows的基本操…

android對象緩存,Android簡單實現 緩存數據

前言1、每一種要緩存的數據都是有對應的versionCode&#xff0c;通過versionCode請求網絡獲取是否需要更新2、提前將要緩存的數據放入assets文件夾中&#xff0c;打包上線。緩存設計代碼實現/*** Created by huangbo on 2017/6/19.** 主要是緩存的工具類** 緩存設計&#xff1a…

通信原理.緒論

今天剛上通信原理的第一節課&#xff0c;沒有涉及過多的講解&#xff0c;只是講了下大概的知識框架。現記錄如下&#xff1a; 目錄1、基本概念消息、信息與信號2、通信系統模型1、信息源2、發送設備3、信道4、接收設備5、信宿6、模擬通信系統模型7、數字通信系統模型8、信源編…

Android版本演進中的兼容性問題

原文&#xff1a;http://android.eoe.cn/topic/summary Android 3.0 的主要變化包括: 不再使用硬件按鍵進行導航 (返回、菜單、搜索和主屏幕)&#xff0c;而是采用虛擬按鍵 (返回&#xff0c;主屏幕和最近的應用)。在操作欄固定菜單。 Android 4.0 則把這些變化帶到了手機平臺。…

css rgba透明_rgba()函數以及CSS中的示例

css rgba透明Introduction: 介紹&#xff1a; Functions are used regularly while we are developing a web page or website. Therefore, to be a good developer you need to master as many functions as you can. This way your coding knowledge will increase as well …

第十七章 擴展Python

第十七章 Python什么都能做&#xff0c;真的是這樣。這門語言功能強大&#xff0c;但有時候速度有點慢。 魚和熊掌兼得 本章討論確實需要進一步提升速度的情形。在這種情況下&#xff0c;最佳的解決方案可能不是完全轉向C語言&#xff08;或其他中低級語言&#xff09;&…

android studio資源二進制,無法自動檢測ADB二進制文件 – Android Studio

我嘗試在Android Studio上測試我的應用程序,但我遇到了困難"waiting for AVD to come online..."我讀過Android設備監視器重置adb會做到這一點,它確實……對于1次測試,當我第二天重新啟動電腦時,我不僅僅是&#xff1a;"waiting for AVD to come online..."…

犀牛腳本:仿迅雷的增強批量下載

迅雷的批量下載滿好用。但是有兩點我不太中意。在這個腳本里會有所增強 1、不能設置保存的文件名。2、不能單獨設置這批下載的線程限制。 使用方法 // 下載從編號001到編號020的圖片&#xff0c;保存名為貓咪寫真*.jpg 使用6個線程 jdlp http://bizhi.zhuoku.com/bizhi/200804/…

為什么使用1 * 1 的卷積核

為什么使用 1* 1卷積核&#xff1f; 作用&#xff1a; 1、實現跨通道的交互和信息整合 2、 進行卷積核通道數的降維和升維 3、 在保持feature map尺度不變的&#xff08;即不損失分辨率&#xff09;的前提下大幅增加非線性特性 跨通道的交互和信息整合 使用1 * 1卷積核&a…

KingPaper初探ThinkPHP3.1.2之擴展函數庫和類庫的使用(四)

在我們做項目的時候TP的系統函數或系統類庫滿足不了我們的需要 所以有些東西需要我們自己去定義&#xff0c;在TP中我們怎么使用自己的函數庫和類庫呢&#xff1f;在TP系統中提供了三個系統函數庫 common.php是全局必須加載的基礎函數庫&#xff0c;在任何時候都可以直接調用&a…