您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“JavaScript中var,let和const的區(qū)別是什么”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“JavaScript中var,let和const的區(qū)別是什么”這篇文章吧。
var
,let
和const
的區(qū)別是什么?var聲明的變量會(huì)掛載在window上,而let和const聲明的變量不會(huì):
var a = 100;console.log(a,window.a); // 100 100let b = 10;console.log(b,window.b); // 10 undefinedconst c = 1;console.log(c,window.c); // 1 undefined
var聲明變量存在變量提升,let和const不存在變量提升:
console.log(a); // undefined ===> a已聲明還沒賦值,默認(rèn)得到undefined值var a = 100;console.log(b); // 報(bào)錯(cuò):b is not defined ===> 找不到b這個(gè)變量let b = 10;console.log(c); // 報(bào)錯(cuò):c is not defined ===> 找不到c這個(gè)變量const c = 10;
let和const聲明形成塊作用域
if(1){ var a = 100; let b = 10;}console.log(a); // 100console.log(b) // 報(bào)錯(cuò):b is not defined ===> 找不到b這個(gè)變量-------------------------------------------------------------if(1){ var a = 100; const c = 1;}console.log(a); // 100console.log(c) // 報(bào)錯(cuò):c is not defined ===> 找不到c這個(gè)變量
同一作用域下let和const不能聲明同名變量,而var可以
var a = 100;console.log(a); // 100var a = 10;console.log(a); // 10-------------------------------------let a = 100; let a = 10; // 控制臺報(bào)錯(cuò):Identifier 'a' has already been declared ===> 標(biāo)識符a已經(jīng)被聲明了。
暫存死區(qū)
var a = 100;if(1){ a = 10; //在當(dāng)前塊作用域中存在a使用let/const聲明的情況下,給a賦值10時(shí),只會(huì)在當(dāng)前作用域找變量a, // 而這時(shí),還未到聲明時(shí)候,所以控制臺Error:a is not defined let a = 1;}
const
/* * 1、一旦聲明必須賦值,不能使用null占位。 * * 2、聲明后不能再修改 * * 3、如果聲明的是復(fù)合類型數(shù)據(jù),可以修改其屬性 * * */const a = 100; const list = [];list[0] = 10;console.log(list); // [10]const obj = {a:100}; obj.name = 'apple';obj.a = 10000; console.log(obj); // {a:10000,name:'apple'}
以上是“JavaScript中var,let和const的區(qū)別是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。