【发布时间】:2018-09-23 20:29:46
【问题描述】:
我已经看到了其中一些问题,但答案似乎从来都不是明确的。我需要在我的哈巴狗视图中遍历一个 javascript 对象。第一次使用哈巴狗,所以我可能会遗漏一些明显的东西。
控制器:
app.get('/search/:keyword', (req, res) => {
scraper
.searchDictionary(req.params.keyword)
.then(words => {
res.render('result', console.log(words))
});
})
这是创建对象的实际函数:
function searchDictionary(searchTerm){
const url = `https://www.dictionary.com/browse/${searchTerm}?s=t`
return fetch(`${url}${searchTerm}`)
.then(response => response.text())
.then(body => {
const words = []
const $ = cheerio.load(body);
$('ol').each(function(i, element){
const $element = $(element)
const $definition = $(element).find('li')
const word = {
keyword: searchTerm,
definition: $definition.text(),
speechParts: $('span.luna-pos').text(),
tenses: $('span.luna-inflected-form').text()
}
words.push(word);
});
return words
});
}
现在,剩下的就是迭代我认为的对象。我不断收到可怕的Cannot read property 'length' of undefined。 Console.log 显示控制器显示正确的数据。
[{ keyword: 'cat',
definition: 'a person, especially a man.a devotee of jazz.',
speechParts: 'nounverb (used with object),verb (used without object),Verb PhrasesIdioms',
tenses: 'cat·ted,cat·ting.cat·ted,cat·ting.' }]
(对象比较多,只是举个例子)
我的观点是这样的:
body
h1
ul
each word in words
li= word.keyword
【问题讨论】:
标签: javascript node.js loops express pug