做JavaScript数组有类似的forEach一个可链接的方法是什么? [英] Do JavaScript arrays have a chainable method similar to forEach?

查看:147
本文介绍了做JavaScript数组有类似的forEach一个可链接的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数组操作方法的一个链条,我想改变阵列中的每个项目的财产。

每个可用的方法有使用这种方式时,一个问题:


  • Array.prototype.forEach不会返回数组

  • Array.prototype.map要求每个项目,则返回

  • Array.prototype.filter需要一个真正的值返回每个项目

是否阵列有一个方法,它允许在一个阵列中的每个项目被操纵,并返回该数组

我已经开始借助任何地图过滤器,但感觉就像一种解决方法,应不是必要的。

一个人为的例子:

  VAR项目= [
   {名称:'史密斯'},
   {名称:'琼斯'},
   {名称:'辛普森'}
];

过滤器:

 返回items.filter(函数(项目){
   item.fullname ='教授'+ item.name;
   返回true;
});

图:

 返回items.map(函数(项目){
   item.fullname ='教授'+ item.name;
   归还物品;
});

的forEach:

  items.forEach(函数(项目){
   item.fullname ='教授'+ item.name;
});返回的物品;

??

 返回items.someMethod(函数(项目){
   item.fullname ='教授'+ item.name;
});


解决方案

没有,有没有这样的方法。常见的辅助库(下划线,的 jQuery的原型, ...)确实有每个迭代方法,返回数组,虽然。

的forEach 方法不返回原来的数组,因为它不是为功能链制造,但执行的副作用。

地图方法是选择这里的工具。它来自函数式编程,其目的是建立一个的新的的改造对象,这自然是从函数返回的数组。通过突变你的对象,而不是创建新的,你无视这种模式,但你仍然可以使用它时,你收益的(突变)的对象。

In a chain of array manipulation methods, I'd like to alter a property of each item in the array.

Each of the available methods has a problem when used this way:

  • Array.prototype.forEach doesn't return the array
  • Array.prototype.map requires that each item is returned
  • Array.prototype.filter requires that a "true" value is returned for each item

Does Array have a method that allows each item in an array to be manipulated, and returns the array?

I've resorted to using either map or filter, but that feels like a workaround which shouldn't be necessary.

A contrived example:

var items = [
   { name: 'Smith' }, 
   { name: 'Jones' }, 
   { name: 'Simpson' }
];

filter:

return items.filter(function(item) {
   item.fullname = 'Professor ' + item.name;
   return true;
});

map:

return items.map(function(item) {
   item.fullname = 'Professor ' + item.name;
   return item;
});

forEach:

items.forEach(function(item) {
   item.fullname = 'Professor ' + item.name;
});

return items;

??:

return items.someMethod(function(item) {
   item.fullname = 'Professor ' + item.name;
});

解决方案

No, there is no such method. Common helper libraries (Underscore, jQuery, Prototype, …) do have each iteration methods that return the array, though.

The forEach method does not return the original array because it is not made for functional chaining, but for executing side effects.

The map method is the tool of choice here. It comes from functional programming, and its purpose is to create a new array of transformed objects, which is naturally returned from the function. By mutating your objects instead of creating new ones, you were disregarding this paradigm, but you can still use it when you return the (mutated) objects.

这篇关于做JavaScript数组有类似的forEach一个可链接的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆