ES6(ES2015)新特性知识点整理
程序员文章站
2022-03-08 22:17:34
...
map, forEach, filter
map
let nums = [1, 3, 5, 7, 9];
console.log(nums); // [ 1, 3, 5, 7, 9 ]
// map方法传入一个函数,遍历数组中的每一个元素并将这个方法作用在元素上,最后返回一个新的数组,不改变原数组
let arr1 = nums.map(i => i + 1);
console.log(arr1); // [ 2, 4, 6, 8, 10 ]
// map操作返回新的数组,所以下面返回false
console.log(arr1 === nums); // false
// map中传入的函数可以有两个参数,e代表遍历过程中当前的元素,i表示当前元素的索引,索引从0开始
let arr2 = nums.map((e, i) => e + i);
console.log(arr2); // [ 1, 4, 7, 10, 13 ]
forEach
let nums = [2, 4, 6, 8, 10];
console.log(nums); // [ 2, 4, 6, 8, 10 ]
// forEach方法传入一个函数,该函数作用于数组中的每一个元素
// forEach没有返回值,且不会修改原来的数组
let arr = nums.forEach(e => e + 1);
console.log(arr); // undefined
console.log(nums); // [ 2, 4, 6, 8, 10 ]
// 依次分行打印2,4,6,8,10
nums.forEach(e => console.log(e));
// i: 0, e: 2
// i: 1, e: 4
// i: 2, e: 6
// i: 3, e: 8
// i: 4, e: 10
nums.forEach((e, i) => console.log('i: ' + i + ', e: ' + e));
filter
let nums = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(nums); // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
// filter传入一个函数,通过遍历数组找出满足该函数的所有元素并返回一个新数组
let odds = nums.filter(e => e % 2 !== 0); // 过滤出所有奇数
console.log(odds); // [ 1, 3, 5, 7 ]
let evens = nums.filter(e => e % 2 === 0); // 过滤出所有偶数
console.log(evens); // [ 2, 4, 6, 8 ]
// i: 5, e: 6
// i: 6, e: 7
// i: 7, e: 8
let bigs = nums.filter((e, i) => {
if (e > 5) {
console.log('i: ' + i + ', e: ' + e);
}
});
Class 类
class Human {
// 类的构造方法
constructor(name, age) {
this.name = name;
this.age = age;
}
// 类的成员方法
say() {
console.log('hello, my name is ' + this.name + ', my age is ' + this.age);
}
static f() {
console.log('hello, I am static method!');
}
}
class Teacher extends Human {
constructor(name, age, major) {
// 调用父类的构造方法
super(name, age);
this.major = major;
}
say() {
// 调用父类的成员方法
super.say();
console.log('I am teaching ' + this.major);
}
test() {
// 调用父类的成员方法
super.say();
}
}
let t1 = new Teacher('zhangsan', 26, 'math');
t1.say();
t1.test();
Teacher.f();
// ---output---
// hello, my name is zhangsan, my age is 26
// I am teaching math
// hello, my name is zhangsan, my age is 26
// hello, I am static method!
arguments & this 局部参数,局部this
局部参数
// Lexical arguments
// 局部参数
function testArgs() {
// arguments代表传入当前函数的参数
for (let arg of arguments) {
console.log(arg);
}
}
// hello
// 1
// 2.5
testArgs('hello', 1, 2.5);
局部this
// Lexical this
// this是局部变量,代表person对象
let person = {
_name: 'zhangsan',
_friends: ['wangwu', 'tom', 'jack'],
prints() {
console.log('-----prints-----');
console.log(this);
this._friends.forEach(name => {
console.log(this._name + ' knows ' + name);
});
console.log('-----prints-----');
}
}
// -----prints-----
// { _name: 'zhangsan',
// _friends: [ 'wangwu', 'tom', 'jack' ],
// prints: [Function: prints] }
// zhangsan knows wangwu
// zhangsan knows tom
// zhangsan knows jack
// -----prints-----
person.prints();
Enhanced Object Literals 增强对象语法
// Enhanced Object Literals
// 增强对象语法
let name = 'zhangsan';
let tag = 'hello';
let obj = {
f() { // 定义方法,原来的写法是f: function(){}
console.log('this is a function');
},
name, // 缩写: name: name
[tag + 'world']: 100 // 动态属性,用[]扩起来的地方是表达式
};
// { f: [Function: f], name: 'zhangsan', helloworld: 100 }
console.log(obj);
Template Strings 字符串模板
// Template Strings
// 字符串模板,使用``和${}
let name = 'zhangsan';
let str = `hello, this is ${name}`;
// hello, this is zhangsan
console.log(str);
let a = 10;
let b = 20;
// 10 + 20 = 30
console.log(`${a} + ${b} = ${a + b}`);
// 使用\n换行
// today is a
// nice day!
console.log(`today is a \n nice day!`);
// 直接在``中换行
// how are you
// this days?
console.log(`how are you
this days?`);
Destructuring 解构
// Destructuring 解构
let [a, ,c] = [1, 5, 8];
// a = 1, c = 8
console.log(`a = ${a}, c = ${c}`);
let person = {
name: 'zhangsan',
age: 25
};
let { name, age } = person;
// name = zhangsan, age = 25
console.log(`name = ${name}, age = ${age}`);
function test({name}) {
console.log(`name = ${name}`);
}
// name = zhangsan
test({name: 'zhangsan'});
// 默认参数
function r({x, y, z = 10}) {
return x + y + z;
}
console.log(r({x: 1, y: 2, z: 3})); // 6
console.log(r({x: 1, y: 2})); // 13
Spread 展开属性
function test(x, ...y) {
// y是长度可变的参数
console.log(y);
return x + y.length;
}
// 这里x = 2, y是长度为3的数组[ 1, 'hello', 3 ]
console.log(test(2, 1, 'hello', 3));
function add(x, y, z) {
return x + y + z;
}
// ...[1, 2, 3]即将数组展开,将每个元素当作一个参数传入函数,x = 1, y = 2, z = 3
console.log(add(...[1, 2, 3]));
let & const
const a = 1;
// a = 2; // 会报错 "TypeError: Assignment to constant variable."
function f() {
{
let x;
{
const x = 'hello';
x = 'world'; // 会报错 "TypeError: Assignment to constant variable."
}
x = 'world';
let x = '123'; // 会报错 "SyntaxError: Identifier 'x' has already been declared"
}
}
f();
Iterators + For..Of 遍历
// fibonacci是一个可遍历的对象
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// 89
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 100)
break;
console.log(n);
}
Generators 迭代器
// 使用function*声明一个迭代器
//遇到yield语句,后面的代码会暂停执行,直到下次调用迭代器的next方法
function* g() {
yield 'a';
yield 'b';
yield 'c';
return 'hello';
}
let generator = g();
// { value: 'a', done: false }
console.log(generator.next());
// { value: 'b', done: false }
console.log(generator.next());
// { value: 'c', done: false }
console.log(generator.next());
// { value: 'hello', done: true }
console.log(generator.next());
// { value: undefined, done: true }
console.log(generator.next());
var fibonacci = {
[Symbol.iterator]: function*() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
}
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// 89
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 100)
break;
console.log(n);
}
Map + Set + WeakMap
let obj = {name: 'zhangsan'};
let s = new Set();
s.add('hello').add(obj).add('hello');
console.log(s.size); // 2
let map = new Map();
map.set('name', 'tom');
map.set('age', 25);
map.set(obj, obj); // object作为map的key
// name = tom, age = 25
console.log(`name = ${map.get('name')}, age = ${map.get('age')}`);
console.log(map.get(obj)); // { name: 'zhangsan' }
// WeakMap只能用Object作为key,不能使用基本数据类型如字符串,整型等
let wm = new WeakMap();
// wm.set('name', 'lily'); // 报错,TypeError: Invalid value used as weak map key
wm.set(obj, 'hello world');
console.log(wm.get(obj)); // hello world
obj = null;
console.log(wm.get(obj)); // undefined
console.log(wm.size); // undefined, WeakMap没有size
Promises 异步操作
function getData() {
return new Promise((resolve, reject) => {
// 模拟耗时的操作(网络,IO...)
setTimeout(() => {
resolve('this is data...');
}, 1000);
});
}
function test() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('error...');
}, 1000);
});
}
getData().then(data => {
console.log(data); // this is data...
});
test().then(() => {
console.log('success');
}).catch(e => {
console.log(e); // error...
});
上一篇: php怎么把图片转换成二进制