简体   繁体   English

Javascript链接方法在一起

[英]Javascript chaining methods together

Lets say I have an array with multiple movies, these movie objects contain things like title/rating/etc... 可以说我有一个包含多部电影的数组,这些电影对象包含诸如title / rating / etc之类的内容。

if I do something like so: 如果我这样做:

let filteredMapList = arr.filter(function(obj){
  return obj.Rating > 8.0;
}).map(function(obj){
  return {title: obj.Title,rating: obj.Rating};
});

This should work and only return movies that are above an 8.0 and return only the Title and Rating in a new object. 这应该起作用,并且仅返回8.0以上的电影,并且仅返回新对象中的“标题”和“等级”。

So my confusion is...which one is exactly running first? 所以我的困惑是……哪一个最先运行? Is map running first and then going through filter or is filter running first and then running map (Which seems odd....even though thats how it's laid out). 是先运行地图,然后通过过滤器,还是先运行过滤器,然后运行地图(这看起来很奇怪...。尽管那是它的布局方式)。

When chaining methods together, how do you exactly....follow the chain. 将方法链接在一起时,如何精确地...遵循链接。 Also does the obj thats getting passed between methods need to be the same? 另外,方法之间传递的obj thats是否必须相同? If not....then im really confused how it actually works. 如果没有,那么我真的很困惑它是如何工作的。

They chain and run exactly in the order they are in. It's a bit more obvious if you rewrite it like this: 它们按照它们所处的顺序进行链接和运行。如果这样重写它,则会更加明显:

let a = arr.filter(function(obj){
  return obj.Rating > 8.0;
});

let b = a.map(function(obj){
  return {title: obj.Title,rating: obj.Rating};
});

The filter happens first and goes to a , then map is called on a and goes to b with your result. filter首先发生,然后转到a ,然后在a map调用map并随结果一起转到b

Chaining functions is the same, you're just skipping the step where you create a variable for each step. 链接功能是相同的,只是跳过为每个步骤创建变量的步骤。

filter runs first, map second. filter先运行,然后再map map receives as an argument = what filter returned. map接收作为参数=返回的filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM