我需要一些帮助来了解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
最佳答案
您的功能就在那里。缺少的主要方面是使用闭包来保存元素。
如果外部函数定义了一个数组,则内部函数将可以访问该数组。那就是关闭。然后,返回的函数将采用单个元素并将其推入components数组。
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 - JavaScript分隔符和闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52959441/