简体   繁体   English

在Javascript中调用函数时,创建全局变量并生成随机数并更新变量

[英]Create global variable and generate random number and update the variable when the function is called in Javascript

I am kinda new in this coding environment and trying to challange myself with exercises. 在这个编码环境中,我有点陌生,并且尝试通过练习来挑战自己。

I am trying to create global variable called quoteNumber and generate a random number and update this variable every time when the function is called. 我正在尝试创建一个名为quoteNumber的全局变量,并生成一个随机数,并在每次调用该函数时更新此变量。

However with the code below, every time I call the function quoteNumber variable stays the same and not updated with new random number. 但是,使用下面的代码,每次我调用函数quoteNumber变量时都保持不变,并且不会使用新的随机数进行更新。

I can solve this putting all variables inside the function but since I am using those variables in different functions I guess it is better for me to create global variable for it. 我可以解决将所有变量放在函数中的问题,但是由于我在不同的函数中使用这些变量,所以我认为最好为它创建全局变量。

What are your suggestions? 您有什么建议?

 var quotes = [{"quote":"Knowledge speaks, but wisdom listens.","author":"Jimi Hendrix"}]; var quoteNumber = 0 ; var generatedQuote = quotes[quoteNumber].quote; var generatedAuthor = quotes[quoteNumber].author; function quoteGenerator () { quoteNumber = Math.floor(Math.random() * 80) + 1; document.getElementById("text").innerHTML = generatedQuote; document.getElementById("author").innerHTML = generatedAuthor; } function share() { document.getElementById("tweet-quote").attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&text=' + encodeURIComponent('"' + generatedQuote + '" ' + generatedAuthor)); } 

PS- I have shortened the quotes variation and put here not to create confusion 附言:我已缩短了报价的变化范围,并在此放置了不要造成混淆

When calling the function you are properly updating the quoteNumber -variable. 调用该函数时,您正在正确更新quoteNumber However, both generatedQuote and generatedAuthor are still the value you set from the beginning. 但是, generatedQuotegeneratedAuthor仍然是您从一开始就设置的值。 So, after setting the quoteNumber to a new value, you will have to do 因此,在将quoteNumber设置为新值之后,您将必须执行

generatedQuote = quotes[quoteNumber].quote;
generatedAuthor = quotes[quoteNumber].author;

To update those variables as well. 也要更新这些变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM