gpt4 book ai didi

javascript - "Return"来自函数未分配给变量

转载 作者:行者123 更新时间:2023-11-28 19:56:28 26 4
gpt4 key购买 nike

我编写了一个函数,它递归地搜索一个对象以从中获取所有特定元素,并返回结果元素数组。

函数本身工作得很好,但由于某种原因,“返回”部分的结果没有分配给调用该函数的变量。

这是函数本身:

var getLinksInObject = function(object){
// Define Variables
var allLinks = [];
var getLinksTimeout = null;

// Function to get the links in an object. Called recursively
var getLinks = function(object){
// Get category and link links
var categories = object.categories;
var links = object.links;

// If there are links
if (links && links.length > 0){
// Push each of them to the allLinks array
for (var i=0, j=links.length; i<j; i++){
allLinks.push(links[i]);
};
};

// If there are category links, push them to the allLinks array
if (categories && categories.length > 0){
for (var i=0, j=categories.length; i<j; i++){
// Build the link
var link = {
title: categories[i].title,
link: categories[i].link
};
// Push the link to allLinks
allLinks.push(link);

// If there are sub-links, run getLinks on that object to get the next level of links
if (categories[i].categories) {
// Reset the listener so it knows we are going for another round
resetTimeout();

// Get the links in the next level
getLinks(categories[i]);
}
};
};
};

// Listens for when the recursive calls finish and returns the result
var resetTimeout = function(){
clearTimeout(getLinksTimeout);
getLinksTimeout = setTimeout(function(){
log(allLinks);
return allLinks;
}, 50);
};

resetTimeout();
getLinks(object);
};

这是一个运行它的测试对象,它与实际对象的结构相匹配:

{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test",
categories: [
{

}
]
}
]
},
{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test"
}
]
}
]
},
{
link: "http://test.com",
title: "This is a test",
categories: [
{

}
]
},
{
link: "http://test.com",
title: "This is a test",
categories: [
{

}
]
}
]
},
{
link: "http://test.com",
title: "This is a test",
categories: [
{
link: "http://test.com",
title: "This is a test",
categories: [
{

}
]
}
]
}
]
}

这是一个重复问题的 fiddle 。您将能够在控制台中看到问题,因为“结果”的日志记录被注销为未定义。

http://jsfiddle.net/KS7LG/

最佳答案

您分配给 getLinksInObject 的函数没有 return 语句。它将始终返回未定义

整个代码中唯一的return语句是这样的:

setTimeout(function(){
console.log(allLinks);
return allLinks;
}, 50);

该函数由 setTimeout 调用,并且 setTimeout 不关注它调用的函数的任何返回值。

setTimeout 是异步的,它稍后运行代码并且不会阻止调用它的函数继续。如果你想处理时间用完后生成的数据,那么你必须从你传递的函数继续这样做,再将数据传回去就太晚了。

关于javascript - "Return"来自函数未分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com