[英]uncaught typeError when using destructuring in arguments
我有这个 function 代码,用于在 javascript 中创建代码片段。 我想知道我是否可以让它看起来更好,因为我认为我所做的这段代码看起来并不专业。
我尝试使用解构,但由于某种原因,我的浏览器向我显示了这条消息 Uncaught TypeError: Cannot read property 'appendChild' of undefined
我想知道是否有任何更好的方法可以将多个参数传递给 javascript 中的 function 为什么它说字符串包含无效字符?
非常感谢。
const create = function ({t, v, p}) { let n = document.createElement(t); n.innerHTML = v; p.appendChild(n); return n; }; // create the list for reference let ul = create({ t: 'ul', v: null, p: document.body });
这是完整的 JS 代码。
const createsnippets = function (e) { // the reference node -- we atually have one ID for headlines let headlines = document.getElementById('headlines'); // utility function to add new HTML DOM element const create = function ({t, v, p}) { let n = document.createElement(t); n.innerHTML = v; p.appendChild(n); return n; }; // create the list for reference let ul = create({ t: 'ul', v: null, p: document.body }); // find all newsarticle classess and add then to snippet in sequence Array.from(document.querySelectorAll('article.newsarticle > h4')).forEach(function (h4) { create('li', h4.textContent + '... ' + h4.nextElementSibling.innerText, ul); }); // insertion re-factors HTMl to ensure the layout (markup and CSS) when displaed headlines.parentNode.insertBefore(ul, headlines.nextSibling) } // once prepared, we can display the loaded content as snippet/collection document.addEventListener('DOMContentLoaded', createsnippets);
您的参数解构很好,但是您以两种不同的方式调用create
。 这个电话很好:
let ul = create({
t: 'ul',
v: null,
p: document.body
});
...但这个不是:
create('li', h4.textContent + ' ... ' + h4.nextElementSibling.innerText, ul);
这将导致您的创建 function 尝试从字符串'li'
解构t
、 v
和p
属性。 解构代码大致翻译为这个,这是第二次调用会发生的情况:
function(param) { // param = 'li'
let t = param.t; // t = 'li'.t -> t = undefined
let v = param.v; // v = 'li'.v -> v = undefined
let p = param.p; // p = 'li'.p -> p = undefined
let n = document.createElement(t); // n = document.createElement(undefined)
n.innerHTML = v;
p.appendChild(n); // undefined.appendChild(n)
return n;
}
也许你打算这样做:
create({
t: 'li',
v: `${h4.textContent} ... ${h4.nextElementSibling.innerText}`,
p: ul
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.