【问题标题】:JavaScript scope issue/errorJavaScript 范围问题/错误
【发布时间】:2018-07-06 10:13:05
【问题描述】:

我收到了邮箱中的脑筋急转弯,这应该需要 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();

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

【问题讨论】:

  • 在您的代码中,将 sentince.push 更改为 sentinces.push,并与赋值右侧的 join 语句相同。

标签: javascript scope this


【解决方案1】:

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

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

  2. 1234563在循环之后)。

这是一个工作示例,如果有任何不清楚的地方,请随时提问:

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

【讨论】:

    【解决方案2】:

    您将变量“sentince”从数组更改为字符串,当您第二次调用函数时,您将“sentince.push(...”调用为字符串类型,变量变量“numWords”在第一次调用后等于 0。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多