省时省力的ES6

栏目: JavaScript · 发布时间: 5年前

内容简介:人一懒起来啊,简直是………上一次发文章都是两个月前了这次就收集一些ES6中的HACK吧!讲真的(会不会是..)…掌握这些技巧。能让我们少写很多行代码哦使用async/await,函数会把返回值放在一个数组中。使用数组解构后就可以把返回值直接赋给相应的变量。

人一懒起来啊,简直是………上一次发文章都是两个月前了 省时省力的ES6

这次就收集一些ES6中的HACK吧!讲真的(会不会是..)…掌握这些技巧。能让我们少写很多行代码哦 省时省力的ES6

1. 变量交换

let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world

// 双击666

2. 接收函数返回的多个结果

使用async/await,函数会把返回值放在一个数组中。使用数组解构后就可以把返回值直接赋给相应的变量。

const [user, account] = await Promise.all([
  fetch('/user'),
  fetch('/account')
])

3. 字符串拼接

let a = 'hello',
    b = 'world';

let _string = `${a} ${b}`

console.log(_string); // "hello world"

4. 函数参数默认值

const notify = (msg, {type='info', timeout, close=true} = {}) => {
  // display notification
    console.log(msg, type, timeout, close)
}

notify('Hi!'); // Hi! info undefined true
notify('Hi!', {type: 'error'}); // Hi! error undefined true
notify('Hi!', {type: 'warn', close: false}); // Hi! warn undefined false

5. 数组

代码不多一行搞定

// 最大值
const max = (arr) => Math.max(...arr);
max([1, 2, 3]) // outputs: 321

// 求和
const sum = (arr) => arr.reduce((a, b) => (a + b), 0)
sum([1, 2, 3, 4]) // output: 10

// 拷贝
let array1 = [1, "3", { a: 1}, 666];
let copyArray = [ ...array1 ];
console.log(copyArray) // [1, "3", {…}, 666]

// 数组连接
const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
// Old way #1
const result = one.concat(two, three)
// Old way #2
const result = [].concat(one, two, three)
// New
const result = [...one, ...two, ...three]

6. 去重

通过 Set 可以轻易的实现数组去重

function dedupe(array) {

return […new Set(array)];

}

let noDupes = dedupe([1, 2, “a”, “a”, { obj1: 999}, 7, 3, 1], { obj1: 999});

console.log(noDupes); // [1, 2, “a”, { obj1: 999}, 7, 3]

通过数组创建 Set 会删除数组中的重复项,而spread运算符会将 Set 转换为 Array

7. 强制要求参数

const throwIfMissing = () => {
    throw new Error('Missing parameter');
}
const func = (requiredParam = throwIfMissing()) => {
    // some implementation
}

8. 删除对象中不需要参数

let { boy1, boy2, ...others } = { boy1: "sunshine", boy2: "sunshine", girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful" };

console.log(others) // { girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful"}

9. 动态属性名

let name = "mael";

let me = {
    [`${name}`]: name,
    age: 24
};

10. for 循环

let a = ['a', 'b', 'c', 'd' ];
// ES6 
for ( var val of a ) {
    console.log( val );
} // "a" "b" "c" "d"
// ES5
for ( var idx in a ) {
    console.log( idx );
}  // 0 1 2 3

11. 定义抽象基类

抽象基类是一种专门用于继承的类。它不能直接构建。主要用例是继承的类具有公共接口。但是, class 尚未利用 abstract 关键字来创建抽象基类,我们可以使用 new.target 来模拟。

class Note {
    constructor() {
        if (new.target === Note) {
            throw new Error('Note cannot be directly constructed.')
        }
    }
}
class ColorNote extends Note {

}
let note = new Note();               // error!
let colorNote = new ColorNote();   // ok

12. 定义惰性范围函数

我们可以使用 generators 来创建一个惰性函数

function* range(start, count) {
    for (let delta = 0; delta < count; delta++) {
        yield start + delta;
    }
}

for (let teenageYear of range(13, 7)) {
    console.log(`Teenage angst @ ${teenageYear}!`);
}

以上所述就是小编给大家介绍的《省时省力的ES6》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP权威指南

HTTP权威指南

David Gourley、Brian Totty / 陈涓、赵振平 / 人民邮电出版社 / 2012-9 / 109.00元

超文本转移协议(Hypertext Transfer Protocol,HTTP)是在万维网上进行通信时所使用的协议方案。HTTP有很多应用,但最著名的是用于web浏览器和web服务器之间的双工通信。 HTTP起初是一个简单的协议,因此你可能会认为关于这个协议没有太多好 说的。但现在,你手上拿着的是却一本两磅重 的书。如果你对我们怎么会写出一本650页 的关于HTTP的书感到奇怪的话,可以去......一起来看看 《HTTP权威指南》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具