[英]Why doesn't this javascript closure work?
So I have this code here that I want to use to dynamically make elements, but it does not work: 因此,我在这里使用了以下代码来动态制作元素,但是它不起作用:
make = {};
elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4'];
elements.forEach(function(element){
make[element] = function() {
document.createElement(element);
}
})
However, when I do: 但是,当我这样做时:
var h1 = make.h1();
I get undefined... Can anyone explain why the element param I am passing to the createElement function doesn't work? 我无法定义...谁能解释为什么我传递给createElement函数的元素参数不起作用? I inspected this to dry and debug and I noticed that the make object has all the correct properties and corresponding functions, however the createElement function doesn't seem to retain the correct value of the element I am tying to pass. 我检查了一下以进行干燥和调试,然后发现make对象具有所有正确的属性和相应的功能,但是createElement函数似乎并未保留我要传递的元素的正确值。
DISCLAIMER: I know there are tons of libraries that I can use but I am doing this for learning and understanding purposes. 免责声明:我知道我可以使用大量的库,但是我这样做是出于学习和理解的目的。 Thank you to anyone who takes some time to explain this to me. 多谢您抽出一些时间向我解释这个问题。 :] :]
您只是缺少一个return语句 :
return document.createElement(element);
This is a more functional approach 这是一种更实用的方法
let elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4'] let make = elements.reduce((acc, elem) => Object.assign(acc, { [elem]: document.createElement(elem) }), {}) console.log(make)
Output 输出量
{
"a": <a></a>,
"div": <div></div>,
"span": <span></span>,
"form": <form></form>,
"h1": <h1></h1>,
"h2": <h2></h2>,
"h3": <h3></h3>,
"h4": <h4></h4>
}
since it is a function passing a array and return a array, I think Array.map is the best fit. 因为它是一个传递数组并返回数组的函数,所以我认为Array.map是最合适的。 see the code below: 参见下面的代码:
elements = ['a', 'div', 'span', 'form', 'h1', 'h2', 'h3', 'h4'];
const make = elements.map(function(element){
return document.createElement(element);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.