欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

初步学习ecmaScript6

程序员文章站 2022-07-08 20:21:39
...
<!DOCTYPE HTML>
<html>
	<head>
		<title>测试es6</title>
	</head>
	<body>
		<h2>欢迎来到es6</h2>
	</body>
	<script type="text/javascript">
		//1.变量 let const
		var a = 1;
		{
			let a = 3;
			console.info('let a',a); //3
		}
		console.info('var a',a); //1

		let b = 3;
		//let b = 4; //Identifier 'b' has already been declared (在let定义的块级作用域内,不能对同一个变量名重复定义)

		const A = 3;//变量一般大写,表示常量
		//A = 4; //Assignment to constant variable.(const定义的常量不允许修改)
		//const A  = 4;//Identifier 'A' has already been declared (与let一样,作用域内是不允许重复定义的)

		//2.for of  forEach循环
		{
			let b = 'welcome use EcmaScript6';
			b = b.split(' ');
			for(var i of b){
				console.log(i);//welcome use EcmaScript6
			}

			b.forEach(function(r){
				console.log('forEach',r);
			});

			b.forEach(r => console.log('forEach => ',r));
		}
		
		//3.关于箭头函数
		//函数的简写形式  (参数)=>函数体
		var arrowFunction1 = function(){ //es5写法
			return 'I`m a arrow function';
		}

		var arrowFunction2 = () => 'I`m a arrow function';//es6写法

		console.info('arrowFunction:',arrowFunction1());
		console.info('arrowFunction:',arrowFunction2());

		let arr =  ['a','b','c'];
		arr.map((vari) => console.info('arrow return ',vari));

		let getFinalPrice = (price, tax=0.7) => console.info(price + price * tax);
		getFinalPrice(500); // 850

		//解构
		var [arrA,arrB,arrC] = arr; //按照顺序将数组的值赋给[]中的变量
		console.log(arrA,arrB,arrC); //a,b,c
		var [arrC,arrA] = arr;
		console.log(arrA,arrC); //b,a

		var a = 1,bb = 4;
		[a,bb] = [bb,a];
		console.log([a,bb])//4,1 可以用来交换数组,不用定义中间临时参数

		//...操作符
		//Spread操作 扩展
		console.info(...[1,2,3,4]) //1 2 3 4

		function foo(x,y,z){
			console.log(x,y,z);
		}
		foo(...[1,2,3,4]);// 1 2 3
		foo(...[{1:4},{2:3}]);//{1:4} {2:3}
		//Rest操作 剩余
		function boo(...args){
			console.info(args);
		}
		boo(1,2,3,4,5,6)//[1, 2, 3, 4, 5, 6]

		//`来组装一堆变量和字符串 ${}来替换变量
		var str1 = 'XiaoMing';
		console.info(`my name is ${str1}`);

		//类 构造函数 继承(基于原型链)
		class Car {
			constructor() {
				console.info('this is car');
			}
			move(){
				console.info('moving');
			}
		}
		var car1 = new Car();
		car1.move();
		class AutoCar extends Car{
			constructor() {
				super();
				console.info('this is auto Car');
			}
		}
		var autoCar = new AutoCar();
		autoCar.move();
	</script>
</html>
相关标签: JavaScript es6