【发布时间】:2018-07-12 18:16:24
【问题描述】:
在使用 nodejs 制作链接 Shortner 脚本时,我遇到了以下问题: 由于我忽略的原因,我的程序进入了无限循环 这是代码:
function makeShort() {
var short = "";
var cond = true;
while(cond){
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < length; i++){
short += possible.charAt(Math.floor(Math.random() * possible.length));
}
let query = {short:short};
Link.findOne(query, (err, link)=>{
if(err) throw err;
if(!link){
console.log("here");
cond = false;
}
});
}
return short;
}
然后在这里使用它:
router.post('/', (req, res)=>{
let short = makeShort();
const newLink = new Link({
url: req.body.url,
short:short
});
newLink.save().then(link => {
res.json(link);
});
});
我的想法是我生成一个随机字符串(5 个字符),然后,如果它存在,我创建另一个,依此类推.. 直到我找到一个未使用的字符串(数据库是空的 btw 所以有没有理由让它无限循环)。
【问题讨论】:
-
它在
for循环中无限循环,因为length没有定义 -
所以将
length中的for循环更改为 5 或您希望字符串的其他长度 -
看起来 cond = true 超出了 var cond = false 的范围
-
我可能错了,但
findOne不会被多次调用,直到cond == false因为它运行回调? -
另外,你可以用这个替换你的 for 循环:
short = (Math.random() * 1000).toString(32).replace(/\./g, '').substr(0, length)
标签: javascript node.js loops infinite