微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

*Chainable* Javascript 方法为数组的每个项目做一些事情

如何解决*Chainable* Javascript 方法为数组的每个项目做一些事情

我正在寻找一种语义方式来对 Javascript 数组中的每个项目执行一些步骤,同时方法链的中间,因为无论出于何种原因I can't use forEach:>

forEach() 对每个数组元素执行一次回调函数;与 map() 或 reduce() 不同,它总是返回未定义的值并且不可链接。典型的用例是在链的末端执行副作用。

Laravel 集合具有 eachtap,它们执行的功能大致相同。

我想我可以只使用 map 并在最后返回原始项目,但我想知道是否有更内置的语义方法来这样做。

解决方法

虽然此解决方案远非完美,但您可以简单地过滤数组并在每个元素上返回 true。

这将允许您保留对数组中每个元素的引用,并为每个元素执行一个操作。

array.someChainableFunction().filter(item => {
    // we do something with each item
    // then return true to keep all the items.
    return true;
}).someOtherChainableFunction()...

const elements = [
  {
    value: 1
  },{
    value: 2
  },{
    value: 3
  },{
    value: 4
  },{
    value: 5
  },];

const output = elements.map(item => {
  item.value++;
  return item;
}).filter(item => {
  // we do something with each items.
  console.log('first map',item);
  // and we return true since we don't want to actually filter the array.
  return true;
}).map(item => {
  item.value++;
  return item;
}).forEach(item => {
  console.log('second map',item);
});

console.log(output);

我强烈建议将它包装在另一个函数中,这样在整个代码中使用它时更容易理解并且不会混淆其他开发人员。

Array.prototype.tap = function (callable) {
      return this.filter(item => {
        callable(item);
        return true;
      });
    }

array.someChainableFunction().tap(item => {
    // we do something with each item
}).someOtherChainableFunction()...

// here,we use an anonymous function rather than an arrow function
// because we need to have access to the `this` context of the Array object.
Array.prototype.tap = function (callable) {
  return this.filter(item => {
    callable(item);
    return true;
  });
}

const elements = [
  {
    value: 1
  },];

const output = elements.map(item => {
  item.value++;
  return item;
}).tap(item => {
  // we use our custom function.
   console.log('first map',item);
}).map(item => {
  item.value++;
  return item;
}).tap(item => {
  console.log('second map',item);
});

console.log(output);

,

我想我可以只使用 map 并在最后返回原始项目,但我想知道是否有更内置的语义方法来这样做。

一个内置方法,它执行 map 的功能,但它返回数组不变,而您的代码不返回每个元素?

或者像 forEach 这样的内置方法,只是它返回数组不变?

我认为不存在。

虽然 map 肯定会在您返回项目不变的情况下执行您想要的操作,但您可以将 forEach() 包装在一个返回数组的可链接函数中:

// add a chainable version of forEach() method to array
function addChainableForEach(array) {
  const newArr = [...array];
  Object.defineProperty(newArr,'chainableForEach',{
    value: function(callback) {
      this.forEach(callback);
      return this;
    },enumerable: false
  });
  return newArr;
}

const arr = [1,2,3];

const arr2 = addChainableForEach(arr)
  .chainableForEach((el) => {
    console.log(`el:`,el);
  });

console.log(`arr2:`,JSON.stringify(arr2));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。