// 例子1
[...new Set(array)]复制代码
// 例子2
const x = {
['a' + '_' + 'b']: 'z'
}
console.log(x.a_b); // z复制代码
// 例子3
fetch('file.json')
.then(data => data.json())
.catch(error => console.error(error))
.finally(() => console.log('finished'));复制代码
// 例子4
function fetch() {
try {
const data = JSON.parse(JSON.stringify(data))
} catch (err) {
console.log(err)
}
};复制代码
// 例子5
// bad
(async () => {
const getList = await getList();
const getAnotherList = await getAnotherList();
})();
// good
(async () => {
const listPromise = getList();
const anotherListPromise = getAnotherList();
await listPromise;
await anotherListPromise;
})();
// good
(async () => {
Promise.all([getList(), getAnotherList()]).then(...);
})();复制代码
// 例子6
// bad
Math.max.apply(null, [14, 3, 77])
// good
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);复制代码
剔除部分属性,将剩下的属性构建一个新的对象json
// 例子 7
let [a, b, ...arr] = [1, 2, 3, 4, 5];
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4, e: 5 };复制代码
// 例子 8
let obj1 = { a: 1, b: 2,c: 3 }
let obj2 = { b: 4, c: 5, d: 6}
let merged = {...obj1, ...obj2};复制代码
// 例子 9
foo::bar;
// 等同于
bar.bind(foo);
foo::bar(...arguments);
// 等同于
bar.apply(foo, arguments);复制代码
若是双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。数组
// 例子 9
var method = obj::obj.foo;
// 等同于
var method = ::obj.foo;
let log = ::console.log;
// 等同于
var log = console.log.bind(console);复制代码
// 例子 10
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
console.log(baz); // "aaa"复制代码
// 例子 11
// bad
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
...
}
}
// good
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
...
}
}复制代码