一、Symbol
1、唯一性
每次调用Symbol()都会返回一个不同的值
任何两个symbol类型的值都不相等,symbol是简单类型的值,不是对象
let s1 = Symbol('foo');
let s2 = Symbol('foo');
s1 === s2 // false
2、私有属性
for-in、for-of、Object.keys()等方法都遍历不到symbol类型的键名
只有Reflect.ownKeys()可以拿到所有类型的键名
3、类型转换
- 不能隐式类型转换
- 可以显示转换成字符串和布尔值,但不能转换成数值
let sym = Symbol('My symbol');
"your symbol is " + sym
// TypeError: can't convert symbol to string
4、Symbol.for()和Symbol.keyFor()
-
Symbol.for()创建symbol类型的值。
传入key值,先检查key值是否存在,如果存在则返回,不存在则创建
let s1 = Symbol.for('detanx');
let s2 = Symbol.for('detanx');
s1 === s2 // true
-
Symbol.keyFor()返回key
不存在则返回undefined
let s1 = Symbol.for("detanx");
Symbol.keyFor(s1) // "detanx"
二、Set和Map数据结构
1、Set
- 类似数组,但成员都是唯一的,没有重复的值
- Set函数可以接受一个数组(或者具有 iterable 接口的其他数据结构)作为参数,用来初始化。
- 应用:数组去重
-
方法:
- .size
- add(val)
- delete(val)
- has(val)
- clear()
遍历方法: - keys()
- values()
- entries()
- forEach()
2、WeakSet
与Set的区别:
- 成员只能是对象,不能是null
- 垃圾回收机制不考虑WeakSet 对该对象的引用,如果其他对象都不再引用该对象,那么垃圾回收机制会自动回收该对象所占用的内存,不考虑该对象还存在于 WeakSet之中。比如DOM对象,解决Set的内存泄露问题
- 方法:
- add(val)
- delete(val)
- has(val)
- 没有size属性
- 不能遍历
3、Map
特点:键可以是任何类型
const m = new Map();
const o = {p: 'Hello World'};
m.set(o, 'content')
m.get(o) // "content"
与Set相比
- Map没有add方法,新增get和set方法
- 遍历方法相同
- Map转成对象
// Map => Object
function strMapToObj(strMap) {
let obj = Object.create(null);
for (let [k,v] of strMap) {
obj[k] = v;
}
return obj;
}
const myMap = new Map()
.set('yes', true)
.set('no', false);
strMapToObj(myMap)
// { yes: true, no: false }
4、WeakMap
与Map的区别:
- 键名只能是对象
- 不能遍历,没有size属性
三、Generator异步编程解决方案
1、特征
- function* 函数名(){}
- Generator函数内部使用yield表达式,定义不同的内部状态,异步操作需要暂停的地方,都用yield语句注明
- 使用:
通过next()调用,返回一个iterator遍历器对象{value:undefined,done:true}
function* funG() {
yield 1
yield 2
yield 3
}
const iter = funG()
iter.next() // {value: 1, done: false}
iter.next() // {value: 2, done: false}
iter.next() // {value: 3, done: false}
iter.next() // {value: undefined, done: true}
2、iterable对象
- 有个Symbol.iterator属性,是一个generator函数,包含yield语句,如下:
let collection = {
items: [],
*[Symbol.iterator]() {
for (let item of this.items) {
yield item;
}
}
};
- 数组、set、map、字符串等都属于iterable对象
- 所有的iterable对象都可以使用for-of遍历
- iterable的遍历方法有entries(),values(),keys(),for-of
3、 yield表达式
- yield表达式本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
- yield命令后面如果不加星号,返回的是整个数组,加了星号就表示返回的是数组的遍历器对象
function* gen(){
yield* ["a", "b", "c"];
}
gen().next() // { value:"a", done:false }
- 任何数据结构只要有 Iterator 接口,就可以被yield遍历*。
let read = (function* () {
yield 'hello';
yield* 'hello';
})();
read.next().value // "hello"
read.next().value // "h"
4、应用:异步任务的封装
var fetch = require('node-fetch');
function* gen(){
var url = 'https://api.github.com/users/github';
var result = yield fetch(url);
console.log(result.bio);
}
使用方法:
var g = gen();
var result = g.next();
result.value.then(function(data){
return data.json();
}).then(function(data){
g.next(data);
});
四、扩展运算符...
1. 将一个数组转为用逗号分隔的参数序列。
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
2. 将类数组转为数组,将字符串转为数组
//类数组转为数组
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]
//字符串转为数组
[...'hello']
// [ "h", "e", "l", "l", "o" ]
3.替代apply方法,将数组作为参数,如:max()和push()
//-------------------max()-------------------------
// ES5 的写法
Math.max.apply(null, [14, 3, 77])
// ES6 的写法
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
//-------------------push()-------------------------
// ES5的 写法
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
Array.prototype.push.apply(arr1, arr2);
// ES6 的写法
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
3.复制数组(浅拷贝)
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;
4.合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
// ES5 的合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
5.扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如Set、 Map、String 结构。
//---------------------Map-------------------------
let map = new Map([
[1, 'one'],
[2, 'two'],
[3, 'three'],
]);
let arr = [...map.keys()]; // [1, 2, 3]
//----------------------Generator-------------------
const go = function*(){
yield 1;
yield 2;
yield 3;
};
//扩展运算符将内部遍历得到的值,转为一个数组
[...go()] // [1, 2, 3]
五、数组的其他方法
1.Array.of()将一组值转化为数组
Array.of(3, 11, 8) // [3,11,8]
2.find(callback)找到数组中第一个符合条件的成员并返回,否则返回undefined
findIndex(callback),返回成员的下标,否则返回-1
[1, 5, 10, 15].find(function(value, index, arr) {
return value > 9;
}) // 10
3.fill()填充数组
['a', 'b', 'c'].fill(7, 1, 2)//1为起始下标,2为结束下标
// ['a', 7, 'c']
4. 用for...of循环进行遍历entries(),values(),keys(),它们都返回一个遍历器对象iterator对象
//遍历键值对
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
//遍历键值
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
//遍历键名
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
//也可以不使用for...of循环,手动调用iterator的next方法进行遍历
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
5. arr.includes(val,startIndex) 判断是否包含给定的值
[1, 2, 3].includes(3, 3); // false
//不兼容时
const contains = (() =>
Array.prototype.includes
? (arr, value) => arr.includes(value)
: (arr, value) => arr.some(el => el === value)
)();
contains(['foo', 'bar'], 'baz'); // => false
6. flat(num),flatMap()降维
flatMap()方法对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。
//flat默认为flat(1),拉平嵌套一层的数组
[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]
//拉平嵌套2层的数组
[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
//不管嵌套多少层都拉平
[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]
// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]
7. at() 支持负索引
const arr = [5, 12, 8, 130, 44];
arr.at(2) // 8
arr.at(-2) // 130
六、对象的方法
1. 属性的遍历(5种方法),返回都是数组
- for...in遍历自身和继承的可枚举属性,不包含Symbol属性
- Object.keys(obj)遍历自身的可枚举属性,不包括Symbol属性
- Object.getOwnPropertyNames(obj)遍历自身的所有属性包括不可枚举属性,但不包括Symbol属性
- Object.getOwnPropertySymbols(obj)返回所有Symbol属性
- Reflect.ownKeys(obj)返回自身的所有属性,包含Symbol属性,也包含不可枚举属性
这5种遍历方法的遍历次序一致 - 首先遍历所有数值键,按照数值升序排列。
- 其次遍历所有字符串键,按照加入时间升序排列。
- 最后遍历所有 Symbol 键,按照加入时间升序排列。
2.super指向原型对象,只能用在构造方法中
super.foo等同于Object.getPrototypeOf(this).foo
3. 对象的解构赋值
- 等号右边必须是一个对象,否则报错
- 解构赋值必须是最后一个参数,否则会报错。
- 浅拷贝
- 不能复制继承自原型对象的属性
- 扩展运算符后面必须是一个变量名,而不能是一个解构赋值表达式
不能这样写let { x, ...{ y, z } } = o;,应该let { x, ...obj } = o;
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }
4. 对象的扩展运算符(...)用于取出参数对象的所有可遍历属性,拷贝到当前对象之中。
let z = { a: 3, b: 4 };
let n = { ...z };
n // { a: 3, b: 4 }
//数组是一种特殊的对象,所以也可以使用
let foo = { ...['a', 'b', 'c'] };
foo
// {0: "a", 1: "b", 2: "c"}
- 对象的扩展运算符等同于使用Object.assign()方法。
let aClone = { ...a };
// 等同于
let aClone = Object.assign({}, a);
七、对象新增方法
1. Object.is(a,b)比较相等
//es5中
NaN===NaN //false
+0===-0 //true
//es6中
Object.is(NaN,NaN) //true
Object.is(+0,-0) //false
2. Object.getOwnPropertyDescriptors()
- es5原本有Object.getOwnPropertyDescriptor(),返回某个对象属性的描述对象
- Object.getOwnPropertyDescriptors()返回指定对象所有自身属性(非继承属性)的描述对象。
const obj = {
foo: 123,
get bar() { return 'abc' }
};
Object.getOwnPropertyDescriptors(obj)
// { foo:
// { value: 123,
// writable: true,
// enumerable: true,
// configurable: true },
// bar:
// { get: [Function: get bar],
// set: undefined,
// enumerable: true,
// configurable: true } }
- 该方法的引入目的,主要是配合Object.defineProperties()方法,解决Object.assign()无法正确拷贝get属性和set属性的问题。
//--------------------------拷贝set属性失败-----------------------------
const source = {
set foo(value) {
console.log(value);
}
};
const target1 = {};
Object.assign(target1, source);
Object.getOwnPropertyDescriptor(target1, 'foo')
// { value: undefined,
// writable: true,
// enumerable: true,
// configurable: true }
const source = {
set foo(value) {
console.log(value);
}
};
const target2 = {};
Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
Object.getOwnPropertyDescriptor(target2, 'foo')
// { get: undefined,
// set: [Function: set foo],
// enumerable: true,
// configurable: true }
3. Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替 __ proto __
// 设置原型对象
Object.setPrototypeOf(object, prototype)
//获取原型对象
Object.getPrototypeOf(obj);
4. Object.keys(),Object.values(),Object.entries()配合for...of遍历对象自身的所有可枚举属性
自己实现Object.entries()方法
// Generator函数的版本
function* entries(obj) {
for (let key of Object.keys(obj)) {
yield [key, obj[key]];
}
}
// 非Generator函数的版本
function entries(obj) {
let arr = [];
for (let key of Object.keys(obj)) {
arr.push([key, obj[key]]);
}
return arr;
}f
5.Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。
八、class
- class的所有方法(包括静态对象和原型方法)都是不可枚举的
- class的所有方法(包括静态对象和原型方法)都没有原型对象,也就是说,不能通过new来调用
-
class必须通过new来调用
4.class内部不能重写类名
重写类名