循环不't停止+dons't更新随机字符串

Loop doesn't stop + doesn't update random string

本文关键字:随机 字符串 更新 停止 循环 +dons      更新时间:2023-09-26

我的脚本有两个问题:它不是每新一轮都随机更新,而是永远运行。但在我看来,它应该两者兼而有之。。如何使循环识别出this.short已更改?

while ( ! this.short) {
    random = Math.random().toString(36).substring(2,7).toUpperCase();
    dpd.links.get({short: random}, function(res, err) {
        if (err)
            cancel('Error', 500);
        if ( ! res.length)
            this.short = random;
    });
}

Math.random()实际上返回一个从当前时间开始播种的伪随机数。因此,它不会为每个循环更新也就不足为奇了。

对于this.shortthis总是指当前函数的"所有者"。所以this.short = random中的this可能与while循环中的this不同。您需要做的是首先将this分配给一个变量。例如:

var current = this;
while (!current.short) {
    ...
    current.short = random;
}