简体   繁体   English

将这些嵌套函数从箭头转换为旧样式以及变量会发生什么

[英]Convert these nested functions from arrow to old style and what happens with variables

I'm trying to find items from one list that are not in items in a second list.我正在尝试从一个列表中查找不在第二个列表中的项目。 Almost by dumb luck I got it to work, but only with arrow functions.几乎是运气不好,我让它工作了,但只有箭头功能。 For me normal functions are easier to read so I tried converting it and the result isn't what I expect.对我来说,普通函数更容易阅读,所以我尝试转换它,但结果不是我所期望的。

data:数据:

const arr1 = [
    {
        "key": 1,
        "val": "one"
    },
    {
        "key": 2,
        "val": "two"
    },
    {
        "key": 3,
        "val": "three"
    }
]

const arr2 = [
    {
        "key": 3,
        "val": "three"
    },
    {
        "key": 4,
        "val": "four"
    },
    {
        "key": 1,
        "val": "one"
    }
]

version 1版本 1

arr1.filter((element) => arr2.findIndex((innerElement) => element.key === innerElement.key) === -1); 
// produces object with key 2

version 2版本 2

arr1.filter(function(element) { 
    return arr2.findIndex(function(innerElement) { 
      element.key === innerElement.key === -1
    })
}) // produces all three objects in arr1

To make the correct one more terse I removed extra parentheses and it still works:为了使正确的更简洁,我删除了额外的括号,它仍然有效:

arr1.filter(element => arr2.findIndex(innerElement => element.key === innerElement.key) === -1);

I'm missing a key aspect here.我在这里遗漏了一个关键方面。 I get that each item in arr1 is passed to a function and that inner function in turn passes its result to another function and the expression has access to both sets of arguments and gets executed.我知道 arr1 中的每个项目都传递给 function,而内部 function 又将其结果传递给另一个 function,表达式可以访问两组 arguments 并被执行。 But I think I have the wrong mental model about the order or something.但我想我对订单或其他东西有错误的心理 model。

Can someone explain what is happening in each step and how to think about it?有人可以解释每个步骤中发生的事情以及如何思考吗? And how do I make it into a normal function?我如何将它变成一个正常的 function?

I'll be dealing with a lot of nested structures and I feel this is a weak area that I'd like to get better in.我将处理很多嵌套结构,我觉得这是一个我想改进的薄弱环节。

Thank you谢谢

You need to return the value of the comparison.您需要返回比较的值。 And the === -1 test must be with the result of findIndex() , not inside its callback. === -1测试必须是findIndex()的结果,而不是在它的回调中。

arr1.filter(function(element) { 
    return arr2.findIndex(function(innerElement) { 
      return element.key === innerElement.key;
    }) === -1;
});

This can be simplified with the some() method.这可以用some()方法简化。

arr1.filter(function(element) {
  return !arr2.some(function(innerElement) {
    return element.key === innerElement.key
  })
})

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

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