JavaScript 分隔符和闭包

标签 javascript loops closures

我需要一些帮助来理解 JavaScript 中的闭包。我需要创建一个函数 (function1),在数组元素之间插入指定的分隔符,如果没有给出分隔符,则插入一个逗号。我试过这样,但它不工作。

function function1(separator)
{
    return function(elements)
    {
        for (var i = 0; i < elements.length; i++)
        return (`${elements}`+ separator);
    };
}


var ex1 = function1("/");
ex1("One"); 
ex1("Two"); 


var ex2 = function1("*");
ex2("One"); 
ex2("Two"); 


var ex3 = function1();
ex3("One");
ex3("Two");


console.log("ex1 is" + ex1() );
console.log("ex2 is " + ex2() );
console.log("ex3 is " + ex3() );

输出应该是

ex1 is One/Two
ex2 is One*Two
ex3 is One,Two

最佳答案

您的函数就快完成了。缺少的主要方面是使用闭包来保存元素。

如果您的外部函数定义了一个数组,则该数组将可供内部函数访问。那就是关闭。然后返回的函数将获取单个元素并将其插入组件数组。

function function1(separator){
    let components = []
    return function(element){
        // this function, even after returned, will have access to components
        // through a closure so you can push into components
        // and return something like components.join(separator)
     }
}

您可能应该检查一个元素,这样您就不会推送空值。

编辑——更多关于闭包
这是基本问题:假设您有一个函数返回这样的函数:

function makelist(seperator){
   return function(element){
      let components = []
      components.push(element)
      return components
   }
 }
 
// now use it
// it returns a function
let myFun = makelist(",")

// but every time you run it, it makes a new components
console.log(myFun("a"))  // ["a"]
console.log(myFun("b"))  // ["b"]
// etc.

这样不好,因为每次调用该函数时您都想压入相同 数组。您可以通过创建函数访问的全局变量来解决这个问题:

var GloablComponents = []

function makelist(seperator){
   return function(element){
      GloablComponents.push(element)
      return GloablComponents
   }
 }
 
// now use it
// it returns a function
let myFun = makelist(",")

// Now every time you use it, it pushes to the same array:
console.log(myFun("a"))  // ["a"]
console.log(myFun("b"))  // ["a", "b"]
// etc.

// But there's a problem:
// You want to make independent functions.
// If you make another, it pushes to myFun list as well:

let newFun = makelist(",")
console.log(newFun("C"))  // ["a", "b", "C"] // not what you want

所以这不好,依赖全局变量也不是一个好习惯,因为它们很难跟踪。

闭包
每个函数都会创建自己的作用域,因此如果您使用一个变量创建一个函数,然后在其中创建另一个函数,则该内部函数将看到该变量,因为它可以访问外部函数的作用域:

function makelist(seperator){
       let aLocalComponent = []         // <------ this out scope
       return function(element){        //          |
          aLocalComponent.push(element) // <-- THIS is referencing
          return aLocalComponent
       }
     }
     
// now use it
// it returns a function
let myFun = makelist(",")

// Now every time you use it, it pushes to the same array
// but it's not a global array, it's the array from
// makelist's scope. That's a closure
console.log(myFun("a"))  // ["a"]
console.log(myFun("b"))  // ["a", "b"]

// Now when make a new function, makelist makes another independent 
// scope. And the new function returned has access to it and its aLocalComponent

let mySecondFun = makelist(",")
console.log(mySecondFun("Z"))  // ["z"]

//At the sametime the old function still accesses the old localcomponentarray:
console.log(myFun("c"))     // only a, b, c

您可以使用相同的想法来确保返回的函数具有相同的分隔符。

关于JavaScript 分隔符和闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52959441/

相关文章:

javascript - javascript 函数 srcElement.nodeName 在 iOS5 中给出了错误的输出

javascript - 滚动动画触发完成处理程序两次

loops - for 循环的前导码的名称?

r - 如何通过汇总 dplyr 函数循环多个数据帧中的数据

c++ - C C++ 数组....需要帮助理解代码

groovy - 在 Groovy 中使用闭包实现接口(interface) - 调用了什么方法?

javascript - 大型应用的回流/布局性能

javascript - Jquery:使用回调函数根据请求预加载图像?

javascript - 构建 NodeJS 模块 - 变量和方法

caching - "Expected type parameter, found reference to type parameter"实现通用缓存结构时