ES6语法糖

一、let局部变量

let与var区别(let有作用域限制)

<script>
	{
		var a = 1;
		let b = 1;
	}
	console.log(a); //1
	consolelog(b); //undifined
</script>

let缺点(var可以定义多个同名变量,而let只能定义一个)

<script>
	var a  =  1;
	var a = 2;
	let b = 1;
	let b = 2;
	console.log(a); //1
	consolelog(b); //error[Uncaught SyntaxError: Identifier 'm' has already been declared]
</script>

二、const常量

常量const(定义后无法改变值)

<script>
	//定义常量
	const PI = "3.1415";
	PI = 3;
	//定义const常量时必须声明时就要初始化
	const MY_AGE; //error(SyntaxError: Missing initializer in const declaration)
</script>

三、数组解构

array

<script>
	//传统解构写法
	let a=1, b=2, c=3;
	console.log(a, b, c);
	
	//es6解构写法
	let [a, b, c] = [a, b, c];
	console.log(a, b, c);
</script>

四、对象解构

object

<script>
	//传统解构写法
	let user = {name: "Helen", age: 18}
	let name1 = user.name;
	let age1 = user.age;
	console.log(name1, age1);
	
	//es6解构写法
	let {name, age} = user; //注意: 解构的变量必须是user中的属性
	console.log(name, age);
</script>

五、模板字符串

${}

<script>
	//1、多行字符串
	let string1 = `Hey,
	can you stop angry now?`
	console.log(string1);
	//2、字符串插入变量和表达式。变量名写在${}中,${}中可以放入JavaScript表达式。
	let name = "Mike";
	let age = 27;
	let info = `My Name is ${name}, I am ${age + 1} years old next year.`;
	console.log(info);
	//My Name is Mike, I am 28 years old next year.
	//3、模板字符串中调用函数
	function f(){
		return "have!";
	}
	let string2 = `Game start, ${f()}`;
	console.log(string2); // Game start, have fun!
</script>

六、声明对象简写

<script>
	const age = 12;
	const name = "lucy";

	//传统方式定义对象
	const p1 = {name: name, age: age};
	console.log(p1);
	
	//es6方式定义-对象简写
	const p2 = {name, age}
	console.log(p2);
</script>

七、定义方法简写

<script>
	//传统
	const person1 = {
		sayHi: funtion(){
			console.log(""Hi);
		}
	}
	pserson.sayHi(); //"Hi"

	//ES6
	const person2 = {
		sayHi(){
			console.log("Hi");
		}
	}
	person2.sayHi(); //"Hi"
</script>

八、对象拓展运算符

…拓展运算符与解构配合使用

<script>
	//1.拷贝对象
	let person1 = {name: "Amy", age: 15};
	let someone = {...person};
	console.log(someone); //{name: "Amy", age: 15}
	//2.合并对象
	let age = {age: 15};
	let name = {name: "Amy"};
	let person2 = {...age, ...name};
	console.log(person); //{age: 15, name: "Amy"}
</script>

九、箭头函数

参数 => 函数体(箭头函数多用于匿名函数的定义)

<script>
	//传统
	var f1 = function(a){
		return a;
	}
	//ES6箭头函数改造
	var f2 = a => a;
	console.log(f2(1));

	//注意:1.当箭头函数没有参数或者有多个参数时,要用()括号括起来
	//2.当箭头函数函数体有多行语句时,用{}包裹起来,表示代码块
	//3.当只有一行代语句,并且需要返回结果时,可以省略{},结果会自动返回
	var f3 = (a, b) => {
		let result = 	a + b;
		return reuslt;
	}
	console.log(f3(6, 2)); // 8

	//前面代码相当于:
	var f4 = (a, b) => a + b;
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值