首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JS中实现方法链接?

如何在JS中实现方法链接?
EN

Stack Overflow用户
提问于 2016-03-09 18:16:13
回答 3查看 232关注 0票数 0

我想链接这些方法调用:

代码语言:javascript
运行
复制
utils.map([1,2,3,4,5], function (el) { return ++el; } )

代码语言:javascript
运行
复制
utils.filter(function (el) {return !el%2; }

它们各自都工作得很好,但以下各项不能正常工作。我怎样才能让下面的代码工作呢?

代码语言:javascript
运行
复制
utils
    .map([1,2,3,4,5], function (el) { return ++el; })
    .filter(function (el) { return !el%2; }

下面是我的utils对象:

代码语言:javascript
运行
复制
var utils = {
    each: function (collection, iteratee){
        return collection.forEach(iteratee);
    },
    map: function (collection, iteratee) {
        return collection.map(iteratee);
    },
    filter: function (collection, predicate) {
        return collection.filter(predicate);
    },
    find: function (collection, predicate) {
        return collection.find(predicate);
    }
}

我知道当我链接两个方法时,参数会发生变化,我只需要提供iteratee而不是一个集合。如何做到这一点?

提前谢谢。如果需要,我愿意解释一个特定的概念。

EN

Stack Overflow用户

发布于 2021-01-14 08:24:51

这是带有ES6类设计的trincot响应的更新版本。

代码语言:javascript
运行
复制
class Collection {
  constructor(collection) {
    if (collection == null || !Array.isArray(collection)) {
      throw new Error('collection is null or not an array');
    }
    this.collection = collection;
  }
  each(iteratee) {
    this.collection.forEach.call(this.collection, iteratee);
    return this;
  }
  map(iteratee) {
    return new Collection(this.collection.map.call(this.collection, iteratee));
  }
  filter(predicate) {
    return new Collection(this.collection.filter.call(this.collection, predicate));
  }
  find(predicate) {
    return this.collection.find.call(this.collection, predicate);
  }
  contains(value) {
    return this.collection.includes.call(this.collection, value);
  }
  get() {
    return this.collection;
  }
}

const result = new Collection([1, 2, 3, 4, 5])
  .map(el => ++el)
  .filter(el => !(el % 2))
  .get();

console.log(result);

console.log(new Collection([1, 2, 3, 4, 5]).find(e => e === 2));
console.log(new Collection([1, 2, 3, 4, 5]).contains(2));
代码语言:javascript
运行
复制
.as-console-wrapper { top: 0; max-height: 100% !important; }

票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35888688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档