es6新特性
es6语法
es6语法用起来是十分方便的,但是有些浏览器还是不支持,但是做大型项目中基本上要用到转码器(babel转码器),可以把es6语法转为es5直接使用。
Tags:javascript
1.变量声明 var => let,const
- 变量提升,let申明的变量不在具有变量提升功能
- 块级作用域,let申明的变量只能在相应块起作用
申明常量cosnt
// let username = ‘小明’;
// var age = 23;
// console.log(‘username :’+ username + ‘ age :’+age);// console.log(username); // undefined
// var username = ‘小明’;
// if(4>3){
// let username = ‘小明’;
// }
// console.log(username); //username is not definedconst k = 100; //常量值不能改变
k = 101;
console.log(k);
2.箭头函数
// es5里函数实现方式两种: 1.定义函数 2.函数申明
/** * 函数申明 */
function max1(){
var a = 10;
var b = 20;
if(a > b){
return a;
}else{
return b;
}
}
/** * 函数定义 */
var max2 = function(a,b){
if (a > b) {
return a;
} else {
return b;
}
}
// console.log(max2(10,21));
/** * es6中函数实现方式 箭头函数 * (参数) => {函数实现} * 特写:只有一个参数 括号可以省略, 函数体只有一条语句,大括号可以省略 * 参数 => 语句1 **/
var max11 = () => {
var a = 10;
var b = 30;
if (a > b) {
return a;
} else {
return b;
}
}
// console.log(max11());
var max12 = (a,b) => {
if (a > b) {
return a;
} else {
return b;
}
}
// console.log(max12(10,23));
// var isLeapYear = (year)=>{
// console.log('是闰年');
// }
var isLeapYear = year => console.log('不是闰年');
isLeapYear();
3.模板字符串
// es5
var a = 20;
var b = 30;
var string = a + "+" + b + "=" + (a + b);
// console.log(string); // 20 + 30 = 50
// es6 模板字符串写法 ejs '<%=a%>'
let a1 = 20;
let b1 = 30;
let string1 = `${ a1}+${ b1}=${ a1+b1}`;
console.log(string1); // 20 + 30 = 50
let item = '<html>'+
'<head>'+
'<title>标题</title>'+
'</head>'+
'<body>'+
'</body>'
'</html>';
let item1 = `<html> <head> <titel>标题2</titel> </head> <body> <h1>一级标题</h1> </body> </html>`;
console.log(item1);
4.解析结构
const Person = {
username:'小明',
age:22,
sex:'男'
}
// let name = Person.username;
// let age = Person.age;
// let sex = Person.sex;
// console.log(`name=${name} sex=${sex} age=${age}`);
// es6
let { username,age,sex} = Person;
console.log(`username=${ username} sex=${ sex} age=${ age}`);
const scores = [90,89,99,87];
var score1 = scores[0];
var score2 = scores[1];
var score3 = scores[2];
var score4 = scores[3];
console.log(`score1=${ score1} score2=${ score2} score3=${ score3}`);
const [s1,s2,s3] = scores;
console.log(`s1=${ s1} s1=${ s1} s3=${ s3}`);
5.函数默认值
// es5
function add(x, y) {
// if (typeof(x) === 'undefined') {
// x = 10;
// }
// if (typeof (y) === 'undefined') {
// y = 20;
// }
var a = x || 10;
var b = y || 20;
return a + b;
}
console.log(add()); // 30 NaN: 是Number类型,表示'不是数字'
// es6
function add2(x = 20, y = 30) {
return x + y;
}
const add3 = (x=20,y=40) => x+y;
console.log(add3());
6.展开运算符
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 10, 20, 30];
console.log(arr2); // [ 1, 2, 3, 10, 20, 30 ]
const obj1 = {
a: 1,
b: 2,
c: 3
}
const obj2 = {
...obj1,
d: 4,
e: 5,
f: 6
}
console.log(obj2); //{ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
7.字面量与class
const name = 'Jane12';
const age = 20;
// es5
var person = {
name: name,
age: age
};
// es6
var person2 = {
name,
age
}
console.log(person2);
还没有评论,来说两句吧...