我在我的邮箱里碰了脑筋急转弯,应该花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();
我假设句子变量的范围是错误的,因为它第一次运行,而不是第二次运行。我想我需要在某处添加一个。
任何帮助将不胜感激,因为我可以阅读其中包含的代码,但是我显然还不能用此编写代码。
最佳答案
主要的错误是您忘记了,如果您要修改全局变量(就此函数而言,函数外部的所有变量都可以称为“全局”),那么在没有您干预的情况下,它将不会采用原始值。例如,如果您在像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();