数组去重
function dedupe(array) {
return Array.from(new Set(array));
}
dedupe([1, 1, 2, 3]) // [1, 2, 3]
let arr = [3, 5, 2, 2, 5, 5];
let unique = [...new Set(arr)];
// [3, 5, 2]
map, filter
let set = new Set([1, 2, 3]);
set = new Set([...set].map(x => x * 2));
// 返回Set结构:{2, 4, 6}
let set = new Set([1, 2, 3, 4, 5]);
set = new Set([...set].filter(x => (x % 2) == 0));
// 返回Set结构:{2, 4}
并集交集
let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);
// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)));
// set {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}
map
const map = new Map([
['name', '张三'],
['title', 'Author']
]);
map.size // 2
map.has('name') // true
map.get('name') // "张三"
map.has('title') // true
map.get('title') // "Author"
Promise
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
异步
async function getTitle(url) {
let response = await fetch(url);
let html = await response.text();
return html.match(/<title>([\s\S]+)<\/title>/i)[1];
}
getTitle('https://tc39.github.io/ecma262/').then(console.log)
// "ECMAScript 2017 Language Specification"
异步其中一个出错后面继续执行
async function f() {
await Promise.reject('出错了')
.catch(e => console.log(e));
return await Promise.resolve('hello world');
}
f()
.then(v => console.log(v))
// 出错了
// hello world
两个异步同时触发
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
风格
// bad
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
}
// good
function getFullName(obj) {
const { firstName, lastName } = obj;
}
// best
function getFullName({ firstName, lastName }) {
}
// bad
const len = items.length;
const itemsCopy = [];
let i;
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
const itemsCopy = [...items];
// bad
[1, 2, 3].map(function (x) {
return x * x;
});
// good
[1, 2, 3].map((x) => {
return x * x;
});
// best
[1, 2, 3].map(x => x * x);
扩展运算符(...)
let aClone = {...a};
// 等同于
let aClone = Object.assgin({}, a);
// 上面仅复制了对象的实例属性,若需克隆完整的对象需复制对象原型的属性
const clone1 = {
_proto_: Object.getPrototypeOf(obj),
...obj
}; // 不适用于非浏览器环境
const clone2 = Object.assign{
Object.create(Object.getPrototypeOf(obj)),
...obj
}; // 推荐
getOwnPropertyDescriptors 方法可以实现一个对象继承另一个对象,之前的写法
const obj = {
_proto_: prot,
foo: 123,
};
// 若去除_proto_
const obj = Object.create(prot);
obj.foo = 123;
// 或者
const obj = Object.assign(
Object.create(prot),
{
foo: 123,
}
);
// 有了Object.getOwnPropertyDescriptors
const obj = Object.create(
prot,
Object.getOwnPropetryDescriptors({
foo: 123,
})
);
Null传导运算
若要判断message.body.user.firstName, 安全写法如下:
const firstName = {
(message
&& message.body
&& message.body.user
&& message.body.user.firstName) || 'default';
}
// 若引入了Null传导运算符
const = firstName = message?.body?.user?.firstName || 'default';
// 只有其中有一个为null 或 undefined 则不再继续运算, 返回 undefined