首页 > 编程 > JavaScript > 正文

ES6 中可以提升幸福度的小功能

2019-11-19 13:20:20
字体:
来源:转载
供稿:网友

一、变量解构赋值的用途

1)交换变量的值

let x = 1;let y = 2;[x, y] = [y, x]

2)从函数返回多个值

// 返回一个数组function example(){  return [1, 2, 4];}let [a, b, c] = example() // 返回一个对象function example(){  return {    foo:1,    bar: 2  }}let {foo, bar} = example(); 或者 ( {foo, bar} = example() )

3)提取JSON数据

let jsonData = { id:42, status: "OK", data: [867, 5309]};let { id, status, data: number} = jsonData;

4)输入模块的指定方法

加载模块时,往往需要指定输入的方法,解构赋值使得输入语句非常清晰

const { SourceMapConsumer, SourceNode } = require("source-map")

5) 数组复制的功能

在es5中,开发者经常使用 concat() 方法克隆数组:

// 在 es5 中克隆数组var colors = [ 'red', 'green', 'blue' ];var clonedColors = colors.concat();console.log(clonedColors); // "[red, green, blue]"

concat() 方法的设计初衷是连接两个数组,如果调用时不传递参数就会返回当前数组的副本。在es6中可以通过不定元素的语法来实现相同的目标:

let colors = [ 'red', 'green', 'blue' ]let [ ...clonedColors ] = colors;console.log(clonedColors); // "[red, green, blue]"

6) 结合Set集合,创建一个无重复元素的数组

function eliminateDuplicates(items) {  return [...new Set(items)]}let numbers = [1, 2, 3, 3, 3, 4, 5];let noDuplicates = eliminateDuplicates(numbers );console.log(noDuplicates ); // [1,2,3,4,5]

7) 使用apply 把两个数据合并成一个

var arra1 = [{ name: '小智', age: 26}]var arra2 = [{ name: '大智', age: 27}]arra1.push.apply(arra1, arra2)console.log(arra1)

二、函数的用处(常见就不多说了)

1)创建立即执行函数表达式

// es5let person = function(name) { return {  getName: function() {   return name;  } }}('小智');console.log(person.getName()); // 小智

在这段代码中,立即执行函数表达式创建了一个包含getName() 方法的新对象,将参数 name 作为该对象的一个私有成员返回给函数的调用者。

只要箭头函数包裹在小括号里,就可以用它实现相同的功能

// es6let person = ((name) => { return {  getName: function() {   return name;  } }})('小智2');console.log(person.getName()); //小智

2.利用参数默认值可以指定某一个参数不得省略,如果省略就抛出一个错误。

function throwEmptyError() {  throw new Error('参数不能为空');}function foo(mustBeParams = throwEmptyError() ){  return mustBeParams();}foo() // 参数不能为空

三、扩展对象的功能性让代码更加简洁

1) 可计算属性名

在es6中,使用方括号可以计算属性名称,如

let lastName ='last name';let person = {  "first name": 'Nicholas',  [lastName]: 'Zakas'}console.log(person['first name']); // "Nicholas"console.log(person[lastName]); // Zakas

2) 利用 Object.assign()合并两个对象

function request(options) { let defaultOptions = {  port: 8000,  type: 'get' } Object.assign(options,defaultOptions); console.log(options)}request({url: 'http://www.baidu.com'})

四、结合es6简洁函数写法,高阶函数的应用

1) tab 函数

// 此处tap函数接受一个 vaule 并返回一个包含value 闭包函数,该函数被执行const tap = (value) => (fn) => ( typeof(fn) === 'function' && fn(value), console.log(value))

tab函数用处:假设你在遍历一个来自服务器的数组,并发现数据错了,因此你想调试一下,看看数组包含了什么,就可以用 tab函数

[1, 2 ,3, 4].forEach((a) => { tap(a)((a)=> {  console.log(a) })});#### 2) once 函数

在很多情况下,我们只需要运行一次给定的函数,发起一次银行支付请求等,这时就可以用到 once 函数。

const once = (fn) => {  let done = false;  return function () {    return done?undefined:((done=true),fn.apply(this,arguments))  }}const doPayment = once(()=>{ console.log('payment is done')})doPayment(); // payment is doneconsole.log(doPayment()); //undefined#### 3) 函数柯里化的应用

开发者编写代码的时候应用的不同阶级编写很多日志,我们可以编写一个如下的日志函数:

const loggerHelper = (mode, initialMessage, errorMessage, lineNo) => { if (mode === 'DEBUG') {  console.debug(initialMessage,errorMessage + 'at line:' + lineNo) } else if (mode === 'ERROR') {  console.error(initialMessage,errorMessage + 'at line:' + lineNo) } else if (mode === 'WARN') {  console.warn(initialMessage,errorMessage + 'at line:' + lineNo) } else  throw "Wrong mode"}

当开发者需要向控制台打印Stats.js文件中的错误时,可以用如下方式:

loggerHelper("ERROR", "ERROR At Stats.js", "Invalid argument passed", 23);

这样对于 我们追求完美可读的程序员来说,可能是不太能接受的,现在用柯里来优化以上代码,
先简要说明什么是函数柯里化:

柯里化是把一个多参数函数转换成一个嵌套的一元函数过程。  

封装一个把把多参数函数转制为一元函数的curry函数

let curry = (fn) => { if (typeof fn !== 'function') {  throw Error('No function provided'); } return function curriedFn(...args) {  // 传入参数是否小于函数参数列表长度,  if (args.length < fn.length) {   return function() {    return curriedFn.apply(null, args.concat([].slice.call(arguments)));   }  }  return fn.apply(null, args) }} let errorLogger = curry(loggerHelper)("ERROR")("ERROR At Stats.js");let debugLogger = curry(loggerHelper)("DEBUG")("ERROR")("Debug At Stats.js");let warnLogger = curry(loggerHelper)("WARN")("Warn")("At Stats.js");// 用于错误errorLogger("Error message", 21)// 用于调试debugLogger('Debug message', 233)// 用于警告warnLogger("Warn message", 34); 

现在我们能够轻松引用上面的柯里化并在各自的上下文中使用它们了。

总结

以上所述是小编给大家介绍的ES6 中可以提升幸福度的小功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表