JavaScript范围问题/错误

时间:2018-01-27 02:42:34

标签: javascript scope this

我在我的邮箱中使用了脑力激荡器,它应该需要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();

我假设句子变量的范围是错误的,因为它第一次运行但不是第二次运行。我想我需要在某处添加一个。 任何帮助将不胜感激,因为我可以读取其中的代码但我显然无法用此编写代码。

2 个答案:

答案 0 :(得分:0)

主要的错误是你忘记了,如果你要修改全局变量(你的函数之外的所有变量都可以被称为“全局”关于这个函数),它将不会在没有你干预的情况下获取原始值。例如,如果在函数var x = 0;之外声明新变量,然后在x = 1之类的函数中修改此变量,则此变量现在将等于1

  1. 您将sentince变量初始化为数组(var sentince = [];),但在第一次执行genSentinces函数后,此变量将是一个字符串(因为您正在执行{ {1}})。出于这个原因,我在函数中声明了新的数组sentince = words.join(' '),我将单词推送到它而不是推送到全局words数组。

  2. 在每次循环迭代时使用sentince减少计数器,但numWords--是一个全局变量,在第一次函数调用后它仍然等于numWords(它是为什么我在循环后添加了0

  3. 以下是工作示例,如果有任何不清楚的话,请随时询问:

    numWords = getRandomInt(2, 8)

答案 1 :(得分:0)

你改变了变量' sentince'从数组到字符串,当你第二次调用函数时,你会在第一次调用后调用' sentince.push(...'到字符串类型和变量变量' numWords'等于0。 / p>