var、let、const關鍵字辨析
varjavascript
var name='Bob'; var name='Tom'; console.log(name) //Tom
//javascript 能夠將變量提高 a = 2 console.log(a); //2 var a //可是初始化的變量是不能提高的 console.log(b); //undefined var b=3;
let arr=[]; for(var i=0;i<2;i++){ arr[i]=function(){ console.log(i) } } arr[0](); //2 arr[1](); //2 //var 沒有塊級做用域,i是全局變量 又由於function不是當即調用函數,循環會很快走到盡頭
letjava
let arr=[]; for(let i=0;i<2;i++){ arr[i]=function(){ console.log(i) } } arr[0](); //0 arr[1](); //1 // 若是是var 結果就是2,2 由於var沒有塊級做用域,i是全局變量 又由於function不是當即調用函數,循環會很快走到盡頭
let b=10; function fn(){ console.log(b); let b=20 } fn(); //會報錯 Cannot access 'b' before initialization
x=3; console.log(x); //會報錯 Cannot access 'b' before initialization let x;
let name='Bob'; let name='Tom'; console.log(name) // 會報錯 Identifier 'name' has already been declared
const函數
if(true){ const num=10; } console.log(num) //會報錯 num is undefined
const PI console.log(PI) //會報錯 Missing initializer in const declaration const P=3.1415; p=3; console.log(p)//會報錯 Assignment to constant variable.
const obj = { name: 'xm', age: 23 } obj.age = 24; console.log(obj); // 能夠操做 obj = {}; //欲修改地址,會報錯 console.log(obj);