简体   繁体   English

Javascript嵌套函数调用始终返回true值

[英]Javascript nested function call always returns value of true

The following javascript code works: 以下javascript代码有效:

const numbers = [10, 15, 20, 25, 30];

function nesting(array, iteratorFunction) {
  let f2 = function(b){
        return false;
      }
  return array.filter(
    function(a){
      return f2(a)
    }   
   );
}

The result is [] when f2 returns false , and [10, 15, 20, 25, 30] if f2 is changed to return true . 如果f2返回false ,则结果为[] ;如果f2更改为true ,则结果为[] [10, 15, 20, 25, 30]

Why doesn't it work correctly after this direction substitution where I simply replaced the variable f2 with the original definition of f2? 为什么在这个方向替换之后,我简单地用f2的原始定义替换了变量f2,它却不能正常工作?

function nesting(array, iteratorFunction) {
  return array.filter(
    function(a){
      return function(b){
        return false;
      }
    }   
   );
}

It returns [10, 15, 20, 25, 30] whether the inner function returns true or false . 内部函数返回true还是false返回[10, 15, 20, 25, 30] Why? 为什么? What piece of knowledge of javascript am I missing? 我缺少JavaScript的哪些知识?

The codes are not equivalent. 代码不相同。

In the first example, you're calling f2 , then using what it returns to filter. 在第一个示例中,您要调用f2 ,然后使用它返回的内容进行过滤。

In the second example, you never call the function ; 在第二个示例中,您永远不会调用该函数 you're returning the uncalled function in the filtering function. 您将在过滤函数中返回未调用的函数。 Since functions themselves are truthy, it allows all elements, regardless of what the function returns. 由于函数本身是真实的,因此它允许所有元素,无论函数返回什么。

To make it equivalent, you need to call the inner function: 为了使其等效,您需要调用内部函数:

. . . 
function(a){
  return (function(b){
    return false;
  })(a); // Add parenthesis to call
}
. . . 

In the second snippet you never execute the f2 function 在第二个片段中,您永远不会执行f2函数

function nesting(array, iteratorFunction) {
  return array.filter(
    function(a){
      return function(b){
        return false;
      }(a)
    }   
   );
}

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

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