JavaScript 范围问题/错误

标签 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();

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

最佳答案

主要的错误是你忘记了,如果你要修改全局变量(对于这个函数来说,你的函数之外的所有变量都可以称为“全局”),如果没有你的干预,它不会采用原始​​值。例如,如果您在函数外部声明新变量,如 var x = 0;,然后在函数内部修改此变量,如 x = 1,则该变量将是现在等于1

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

  2. 您使用 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/

相关文章:

Jquery (this)closest 不起作用?

javascript - 没有常量引用 "this"的 JS 类用于成员访问

javascript - 如何删除使用 css last-child 添加的样式

javascript - NodeJS Javascript for 循环更改内容

javascript - 这段代码在我的 Wordpress 博客上有什么作用?恶意软件?

javascript - jQuery 为每个元素分配超时事件处理程序

c++ - 使用this指针可以吗?

javascript - 我如何计算 Angular 中选中的复选框?

groovy - Groovy 元类的范围?

c++ - 无法在 C++ 中解析符号