问题
I am new to JavaScript and I currently studying closures. Below you can see my code that is supposed to print any given array with a specified separator between each element. The thing is that if i try to create an array and print it in the makePath() function, everything works just fine. But when I try to do the same in the main function, it just doesn't work. I also have one more problem when I try to join the separator with the array, The separator is printed at the end of the list and I don't want that.
var makePath;
function makePath(separator) {
let comp = []
return function(element)
{
comp.push(element)
return comp.join(separator)
}
}
var path0 = makePath("/");
path0("A");
path0("B");
path0("C");
console.log("path 0 is " + path0());
var main = function() {
var path1 = makePath("/");
path1("A");
path1("B");
path1("C");
var path2 = makePath("-->");
path2("Berlin");
path2("San Francisco");
path2("Vancouver");
var path3 = makePath();
path3("A");
path3("B");
path3("C");
window.console.log("path 1 is " + path1());
window.console.log("path 2 is " + path2());
window.console.log("path 3 is " + path3());
}
The output is:
path 0 is A/B/C/
回答1:
Q1: Why the makePath
functions in main() didn't work?
Ans: You only declare the main function, but haven't call it, just add main()
in the end, it will work!
Q2: Why there's an additional separator at the end of your output string?
Ans: The problem is in here: console.log("path 0 is " + path0());
.
You called an additional path0()
, which makes your Array comp
became ['A', 'B', 'C', ' ' ].
You can modify your code like this:
var path0 = makePath("/");
path0("A");
path0("B");
let finalResult = path0("C");
console.log("path 0 is " + finalResult);
Without the additional call, the result should work as you expected.
来源:https://stackoverflow.com/questions/52970559/javascript-closures-function