我在邮箱里看到了脑筋急转弯,预计需要 20 分钟,但显然,我陷入了我使 Chrome 崩溃的范围。这个想法是为您提供一个字符串。然后,您可以使用该字符串生成类似于 lorum ipsum 的随机句子。
var words = "The sky above the port was the color of television, tuned to a
dead channel. All this happened, more or less. I had the story, bit by bit,
from various people, and, as generally happens in such cases, each time it
was a different story. It was a pleasure to burn.";
var wordList = words.split(' ');
var numWords = getRandomInt(2, 8);
var numSentinces = getRandomInt(8, 40);
var sentinces = [];
var sentince = [];
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function genSentinces() {
while (numWords > 0) {
sentince.push(wordList[getRandomInt(0, wordList.length)]);
numWords--;
}
sentince = sentince.join(' ');
console.log(sentince)
return sentince;
}
genSentinces();
genSentinces();
我假设句子变量的范围是错误的,因为它是第一次运行,但不是第二次运行。我想我需要在某处添加一个 this 。 任何帮助将不胜感激,因为我可以阅读其中包含此代码的代码,但我显然还无法用此编写代码。
最佳答案
主要的错误是你忘记了,如果你要修改全局变量(对于这个函数来说,你的函数之外的所有变量都可以称为“全局”),如果没有你的干预,它不会采用原始值。例如,如果您在函数外部声明新变量,如 var x = 0;
,然后在函数内部修改此变量,如 x = 1
,则该变量将是现在等于1
。
您将
sentince
变量初始化为数组 (var Sentince = [];
),但在第一次执行genSentinces
函数之后,此变量将是一个字符串(因为您正在执行sentince = Words.join(' ')
)。因此,我在函数内声明了新数组words
,并将单词推送到其中,而不是推送到全局sentince
数组。您使用
numWords--
来减少每次循环迭代的计数器,但numWords
是一个全局变量,它仍然等于0
第一次函数调用后(这就是我在循环后添加numWords = getRandomInt(2, 8)
的原因)。
这是工作示例,如果有任何不清楚的地方,请随时询问:
var words = "The sky above the port was the color of television, tuned to a dead channel. All this happened, more or less. I had the story, bit by bit, from various people, and, as generally happens in such cases, each time it was a different story. It was a pleasure to burn.";
var wordList = words.split(' ');
var numWords = getRandomInt(2, 8);
var numSentinces = getRandomInt(8, 40);
var sentinces = [];
var sentince = [];
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function genSentinces() {
var words = [];
while (numWords > 0) {
words.push(wordList[getRandomInt(0, wordList.length)]);
numWords--;
}
numWords = getRandomInt(2, 8);
sentince = words.join(' ');
console.log(sentince)
return sentince;
}
genSentinces();
genSentinces();
关于JavaScript 范围问题/错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472074/