gpt4 book ai didi

Javascript 从嵌套函数中返回

转载 作者:行者123 更新时间:2023-11-30 07:59:26 26 4
gpt4 key购买 nike

我试图在路由中返回随机化器函数的输出...我一直得到“未定义”- 但不知道我做错了什么...

var randomizer = function() {
// A load of stuff happens here.. and functions that are needed by the pullOut function (I've removed for brevity)
var pullOut = function(pick) {

if (playerList.length !== pick) {
var random_item = getRandomItem(list, weight);

if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
playerList.push(random_item);
}
pullOut(pick);
} else {
console.log(playerList)
return playerList;
}
}
return pullOut(pick);
}


router.route('/ordercreated')
.post(function(req, res) {

var orderedItems = req.body.line_items;
// I foreach through all the items - calling the randomizer function on each one...
_.forEach(orderedItems, function(n) {
Pack.findOne({
'product_id': n.variant_id
}, function(err, pack) {
if (err) {
return res.send(err);
}
if (pack) {

var list = [];
var weight = [];

_.forEach(pack.playerData, function(n) {
list.push(n.name);
weight.push(parseInt(n.chance));
});


console.log('randomizing', randomizer(pack.title, list, weight, n.qty, pack.pick));
}
});
});

res.sendStatus(200);

})

最佳答案

您的“pullOut”函数会调用自身,但会丢弃该调用的结果。

var randomizer = function() {
// A load of stuff happens here.. and functions that are needed by the
// pullOut function (I've removed for brevity)
var pullOut = function(pick) {

if (playerList.length !== pick) {
var random_item = getRandomItem(list, weight);

if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
playerList.push(random_item);
}
return pullOut(pick); // <--- add return
} else {
console.log(playerList)
return playerList;
}
}
return pullOut(pick);
}

如果没有 return,当函数通过主 if 语句执行该路径时,它将返回 undefined

关于Javascript 从嵌套函数中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31943541/

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