关于let , var , const 的使用与区别
程序员文章站
2022-05-20 19:50:27
...
let
let 声明变量
let a;
let b,c,d;
let e=100;
let f=200, g=300;
let不允许重复声明
let a = 2;
let a = 3;
console.log(a);//Identifier 'a' has already been declared
let块儿级作用域
if(){ } else {} for(){ } while(){ } { } 都是代码块,函数不算
{
let c = 4;
console.log(c);//4
}
console.log(c);// c is not defined
let 不存在变量提升
console.log(a); //Cannot access 'a' before initialization
let a = 'hahaha';
var
var声明变量
var a;
var b,c,d;
var e=100;
var f=200, g=300;
var 可以声明多次
var a = 2;
var a = 3;
console.log(a);//3
var声明的变量没有局部作用域
{
var b = 3;
console.log(b);//3
}
console.log(b);//3
var声明的变量可以进行提升
console.log(a); //undefined
let a = 'hahaha';
const 关键字用来声明常量
1) 一旦声明必须赋值,否则报错
const b;
console.log(b);//Missing initializer in const declaration(const声明中缺少初始值)
2) 不允许重复声明
const c= 4;
const c= 5;
console.log(c)//Identifier 'c' has already been declared(标识符“ c”已被声明)
3) 值不允许修改
const a =5;
a=6;
console.log(a);//TypeError: Assignment to constant variable.
4) 块儿级作用域(和let一样)
{
const A = 100;
console.log(A); //100
}
console.log(A);// A is not defined
注:
常量的名称一般为 『大写』 (小写也不错)
关于数组和对象的元素的修改(只改变地址里的数据正常显示,修改常量值会报错)
const TEAM = ['UZI','MLXG','LETME','meiko'];
TEAM.push('xiye');
TEAM[0] = '小狗';
console.log(TEAM) // ["小狗", "MLXG", "LETME", "meiko", "xiye"]
const MIDDLE = {
name: 'Faker'
};
console.log(MIDDLE) //{name: "瓜皮"}
MIDDLE = 200; // Assignment to constant variable.
图片
上一篇: 17.ROS中的坐标系管理系统
下一篇: ES6 Promise用法