1、解构赋值
数组:
let arr=[1,2,3];let [a,b,c]=arr;
console.log(a);//1
let arr2=[1,2,3];let [a,...b]=arr2;
console.log(a);//1
console.log(b.length);//2个
console.log(b);//相当于剩余项值为[2,3]
对象:
obj={a: 10, b: 20, c: 30, d: 40};
let {a, b, ...rest} = obj;
console.log(a);//10
console.log(b);//20
console.log(rest);//相当于剩余项值为{c: 30, d: 40}
应用示例如图所示:
function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum; }
add(2, 5, 3) // 10
function add(x, y) { return x + y; } var numbers = [4, 38]; add(...numbers) // 42
// ES5 [1, 2].concat(more)
// ES6 [1, 2, ...more]
// ES5的合并数组 arr1.concat(arr2, arr3); // [ 'a', 'b', 'c', 'd', 'e' ]
// ES6的合并数组 [...arr1, ...arr2, ...arr3] // [ 'a', 'b', 'c', 'd', 'e' ]
二、对象赋值合并
var o1 = {a: 1}; var o2 = {b: 2}; var o3 = {c: 3};
var obj = Object.assign(o1, o2, o3);
console.log(obj); //{a: 1, b: 2, c: 3}
console.log(o1); //{a: 1, b: 2, c: 3}, 目标对象o1被改变了
三、箭头函数及foreach遍历、数组过滤filter
var foo = function(){return 1;}; //等价于 let foo = () => 1;
let nums = [1,2,3,5,10]; let fives = []; nums.forEach(v => { if (v % 5 === 0) fives.push(v); }); console.log(fives); //[5,10]
var ages = [32, 33, 16, 40];
var newAges= ages.filter(age=> age>18);//[32,33,40]
注意(v)中括号可以省略,只有一个值时;
四、模板字符串
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
let str="hahav";
console.log(str.includes('a'));//true,真判断是否存在方式一
console.log(str.indexOf('a'));//4,>0判断是否存在方式二
参考es6地址
https://www.runoob.com/w3cnote/es6-tutorial.html