Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

高阶函数的优点在哪里? #3

Open
hxkuc opened this issue Jun 14, 2018 · 1 comment
Open

高阶函数的优点在哪里? #3

hxkuc opened this issue Jun 14, 2018 · 1 comment

Comments

@hxkuc
Copy link
Owner

hxkuc commented Jun 14, 2018

有个问题关于高阶函数,下面做一个简单的比较
有一个数组如下

let arr = [
  {name: '张三', age: 15, jjLength: 13},
  {name: '李四', age: 23, jjLength: 17},
  {name: '王五', age: 52, jjLength: 10},
  {name: '赵六', age: 7, jjLength: 63},
]

要对这个数组按照age或jjlength进行排序,我们使用sort函数先对age进行排序

arr.sort((a, b) => {
  return a.age > b.age ? 1 : a.age < b.age ? -1 : 0
})
console.log(arr)

再对jjLength进行排序

arr.sort((a, b) => {
  return a.jjLength > b.jjLength ? 1 : a.jjLength < b.jjLength ? -1 : 0
})
console.log(arr)

以上是两个函数,我们可以进行简单的封装,按照正常的思路来,这个估计是大部分人的想法,也比较好理解,如下

function mySort (arr, type) {
  arr.sort(function (a, b) {
    return a[type] > b[type] ? 1 : a[type] < b[type] ? -1 : 0
  })
}
mySort(arr, 'age')

传入一个数组然后传入要针对排序的属性就可以了,方便易于理解

那么我们再来看一下高阶函数的实现

let mySort = type => (a, b) => {
  return a[type] > b[type] ? 1 : a[type] < b[type] ? -1 : 0
}
arr.sort(mySort('jjLength'))

对此你觉得哪个容易理解呢,各自的有缺点在哪里呢??

@hxkuc
Copy link
Owner Author

hxkuc commented Jun 14, 2018

高阶函数的优点在于把函数流程分块化,等于流水线按块划分,调用不同的块可以造出不同的东西

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant