[英]Node.js Function Undefined
我正在编写解析从网页获取的 HTML 的代码,我遇到了一个问题,我的 function 返回undefined
。
function getVideoUrl(category) {
PathLoader.load(config.category_url + category['id']).then(function(document) {
let soup = new JSSoup(document);
let tag = soup.findAll("li");
tag.forEach((tag) => {
if (tag.attrs.class) {
if (tag.attrs.class.startsWith("pcVideoListItem")) {
return config.view_video_url + tag.attrs['_vkey'];
}
}
});
});
}
let random_category = getRandomCategory();
let video_url = getVideoUrl(random_category);
console.log(video_url);
正如您可能已经猜到的那样,function getVideoUrl()
是返回undefined
的那个。 我完全糊涂了。
您不会从getVideoUrl
方法返回任何内容。 forEach
循环遍历元素数组,但它不返回任何高于它的内容。
我认为您应该使用find
而不是forEach
。
尝试:
const tags = soup.findAll("li");
const matchedTag = tags.find(tag => tag.attrs.class && tag.attrs.class.startsWith("pcVideoListItem"));
const videoUrl = matchedTag ? `${config.view_video_url}${matchedTag.attrs['_vkey']}` : '';
此外,仅当您打算更改变量的值时才使用let
。 否则总是使用const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.