为什么这个需要的函数的variables参数返回undefined?
我的HTML模板变得太长,所以我决定把它们放在一个单独的文件中(我使用的是Babel.js):
template.js:
exports.contents = function(data) { return `<html> <head> <title>Book name</title> </head> <body> <h2>${data}</h2> </body> </html>` }
在这里使用:
app.js:
fs.readFile(filename, 'utf8', (err, data) => { // I'm converting Markdown to HTML. In this case the // the file just has the text: This is some data let result = convertToHTML(data) fs.writeFile("untitled.html", result, (err) => { if (err) { console.log(err) } else { console.log(result) console.log(template.contents(result)) } }) })
console.log(result)
输出正确的结果:
<p>This is some data</p>
但是console.log(template.contents(result))
输出这个:
<html> <head> <title>Book name</title> </head> <body> <h2>undefined</h2> </body> </html>
这里发生了什么事?
编辑:
这里是convertToHTML函数:
function convertToHTML(markdownSource) { let data = markdownSource.split(/\n\n|^>(?!.)/gm) , orig = data.slice() , conversions = [ convertHeadings, convertQuotes, convertDashes, convertStyling, convertParagraphs ] // use an original copy so the match comparison is always clean for (let i = 0, l = orig.length; i < l; ++i) { for (let conversion of conversions) { let result = conversion(data[i], orig[i], orig[i - 1]) if (result !== undefined) { data[i] = result } } } return data.join('\n\n') }
这很简单:
console.log(result); console.log(template.contents());
也许你想传递一些东西给你的函数? 🙂