The difference between const and let in ES6 and the destructuring assignment of variables

1. The let keyword

The let keyword is used to declare variables. Variables declared using let have several characteristics:

  1. Duplicate statement not allowed

  2. block scope

  3. exist variable hoisting

  4. does not affect the scope chain

Application scenario: If you want to make your code more advanced, you can use let to declare variables in the future

2. The const keyword

The const keyword is used to declare the quantity, and the const declaration has the following characteristics:

  1. declaration must assign an initial value

  2. The identifier is generally not written

  3. Duplicate statement not allowed

  4. Value does not allow modification

  5. block scope

Note: object property modification and array element change will not trigger const error

Application scenario: declare object type using const, non-object type declaration choose let

3. Object deconstruction assignment

ES6 allows to extract values ​​from arrays and objects and copy variables according to a certain pattern, which is called destructuring assignment.

//ES6 允许按照一定模式从数组和对象中提取值,对变量进行赋值,这被称为解构赋值。
//1. 数组解构赋值
const name = ["yimao","ermao","sanmao","simao"];
let [a,b,c,d] = name;
console.log(a);
console.log(b);
console.log(c);
console.log(d);

//2. 对象的解构赋值
const zhao = {
	name: "赵本山",
	age: 34,
	xiaopin: function () {
		console.log("我可以");
	}
};
let {name,age,xiaopin} = zhao;
console.log(name);
console.log(age);
console.log(xiaopin); 
xiaopin();

let { xiaopin } = zhao;
xiaopin();

Note: If you frequently use object methods and array elements, you can use the destructuring assignment form

4. Template string

Template string (template string) is an enhanced string, marked with backticks (`), features:

  1. Newline characters can appear in the string

  2. Variables can be output in the form of ${xxx}

// ES6 引入新的声明字符串的方式 『``』 '' ""
// 1.声明
let str = `我也是一个字符串啊`;
console.log(str,typeof str); 

// 2.内容中可以直接出现换行符
let str =  `<ul>
				<li>哈哈</li>
				<li>嘿嘿</li>
				<li>呵呵</li>
			</ul>`;
    
// 3.变量拼接
let a = "今天";
let b = `${a}星期四`;
console.log(b);

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/120417895