简体   繁体   English

向JavaScript变量添加整数

[英]Adding an integer to a JavaScript variable

I have a variable declared here: 我在这里声明了一个变量:

var quizScore = 0;

And I want to add a number to it each time the correctAnswer() function runs: 而且我想在每次正确运行correctAnswer()函数时向其添加一个数字:

function correctAnswer(){
  quizScore+1;
    console.log ( 'correct answer selected: quizscore = ' + quizScore );
}

I added a console log for debugging. 我添加了用于调试的控制台日志。 It works, so the function is being called, but it is not adding the score. 它可以工作,因此可以调用该函数,但不添加分数。 Do I need to parse this to an integer? 我需要将其解析为整数吗? I can't work out what the +1 needs to be to work correctly. 我无法确定+1才能正常工作。

You can go here and you will see that clicking "Lightning Bolt" for question 1 shows "correct answer" in the console, but doesn't add to the score variable. 您可以转到此处,您会看到在问题1中单击“闪电”会在控制台中显示“正确答案”,但不会添加到score变量中。

Do it like this: 像这样做:

function correctAnswer(){
    console.log ( 'correct answer selected: quizscore = ' + (++quizScore) );
}

You just need to assign the +1 to quizScore variable. 您只需要将+1分配给quizScore变量。 This may be the fastest way to add 1 and display it in one line 这可能是最快的方法,将1加一并显示在一行中

You're adding one to whatever value is in quizScore , and doing nothing with the result. 您要在quizScore任何值上加上一个,而对结果不执行任何操作。

You need quizScore = quizScore + 1 . 您需要quizScore = quizScore + 1

Keep quizscore as global variable. 将quizscore保留为全局变量。 And secondly change the line no.1 of your correctAnswer() function to 然后将您的correctAnswer()函数的第一行更改为

quizScore = quizScore + 1;

You can use self-memorizing function not to pollute global environment with variables like so: 您可以使用自记忆功能,而不用这样的变量污染全局环境:

function correctAnswer() {
    correctAnswer.quizScore = (correctAnswer.quizScore || 0) + 1;
    console.log("QuizScore : " + correctAnswer.quizScore);
}

for (var i = 0; i < 10; i++) {
    correctAnswer(); // output 1 2 3 4 5 6 7 8 9 10
}

Right now, when you do this: 现在,当您执行此操作时:

quizscore+1;

You add one to it but it doesn't assign the change to the variable. 您向其中添加了一个变量,但它没有将更改分配给变量。 One reason for this is that sometimes you may want to add a number to the variable long enough to perform an operation but you don't want it to change. 这样做的一个原因是,有时您可能想在变量中添加一个数字足够长的时间来执行一个操作,但又不想更改它。

// quiz score is left alone
var nextscore = quizscore + 1

Here are the different ways to actually assign it: 这是实际分配它的不同方法:

// temporarily adds 1 to quizscore, then saves it to quizscore
quizscore = quizscore + 1

// adds one to quizscore after it's used in an expression
quizscore++

// adds one to quizscore before it's used in an expression
++quizscore

So if you did something like this: 因此,如果您执行以下操作:

var nextscore = ++quizscore + 1;

You would both increment the current score and predict the next score. 您既可以增加当前分数,又可以预测下一个分数。

Read more: Expressions and Operators 阅读更多: 表达式和运算符

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

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