1. let和var和const
var
声明的变量会越域
可以声明多次
会变量提升(声明前调用会报undefined)
let
声明的变量有严格局部作用域
只能声明一次
不会变量提升(声明前调用会报错)
const
声明后不能修改
2. 解构表达式
数组解构
let arr = [1,2,3]
//旧
let a = arr[0];
let b = arr[1];
let c = arr[2];
//新
let [a,b,c] = arr;
对象解构
const person = {name:"jack", age:23, language:["java","js","css"]}
//旧
const name = person.name;
const age = person.age;
const language = person.language;
//新可选择重命名赋值
const {name:abc, age, language} = person;
console.log(abc, age, language);
字符串模板
function fun(){
return '这是一个函数'
}
let info = `我是${abc},今年${age+10}岁了。我想说:${fun()}`;
函数参数的默认值
function add (a, b = 1){
return a + b;
}
console.log(add(20));// 输出为 21
不定参数
function fun(...values){
console.log(values.length);
}
fun(1,2,3) //输出为3
箭头函数
let print = obj => console.log(obj);
let sum = function(a, b){
c = a + b;
return a + c;
}
let sum2 = (a, b) => {
c = a + b;
return a + c;
}
箭头函数+解构表达式
const person = {
name: "jack",
age: 23
}
//旧
function hello(person){
console.log("hello, "+ person.name);
}
//新1
let hello2 = (param) => console.log("hello, "+ person.name);
//新2
let hollo3 = ({name}) => console.log("hello, "+ name);
hello3(person);
3. 对象优化
对象追加
const source = { a: 1};
const source1 = { b: 2};
const source2 = { c: 3};
Object.assign(source, source1, source2);
对象的函数属性简写
let person3 = {
name: "jack",
//以前
eat: function (food){
console.log(this.name + "在吃" + food);
},
//箭头函数this不能使用,需要对象.属性
eat2: food => console.log(person3.name + "在吃" + food),
eat3(food){
console.log(this.name + "在吃" + food);
}
}
拷贝对象(深拷贝)
let person1 = { name: "JACK", age: 23};
let someone = {...person1};
合并对象
let p1 = {name: "BOB"}
let p2 = {age: 25}
let p3 = {...p1, ...p2}
4. map
let arr = ['1', '20', '-5', '3'];
arr = arr.map(item=> item*2);