简体   繁体   English

函数不返回值

[英]Function does not return value

I've only started to learn how to refactor code and I'm failing at abstracting a simple function. 我只是开始学习如何重构代码,而我在抽象一个简单函数方面却失败了。 I pass the parameters into checkAnwser and it works, but count is "lost" 我将参数传递到checkAnwser并且可以运行,但是count “丢失”了

I can't get/append "count" here: 我无法在此处获取/添加“计数”:

jsfiddle 的jsfiddle

<input data-correctanswer="javascript" id="answer1" name="" type="text">This works fine (no special chars)
<br/>
<button id="btn1">check 1</button>
<br/>
<input data-correctanswer="jávascripté" id="answer2" name="" type="text"> 
<br/>
<button id="btn2">check 2</button>
<div style="border: 1px solid;" id="result"></div>

Javascript: 使用Javascript:

 $(document).ready(function () {

         var count;
         $('#btn1').click(function () {
             checkAnswer($('#answer1').data('correctanswer'), $('#answer1').val());
             $('#result').append('result: ').append(count); <-- does not read count
     }); // end of click
     $('#btn2').click(function () {
         checkAnswer($('#answer2').data('correctanswer'), $('#answer2').val());
         $('#result').append('result: ').append(count); // <-- does not read count
     }); // end of click


         function checkAnswer(coorAns, UserAnswer) {
             var count = 0;
             //  var coorAns = $('input[type=text]').data('correctanswer');
             //  var UserAnswer = $('input[type=text]').val();
             var mistakesAllowed = 1;

             if (UserAnswer === coorAns) {
                 count = count + 2;
             }
             for (i = 0; i < coorAns.length; i++) {
                 if (coorAns.charAt(i) !== UserAnswer.charAt(i)) {
                     mistakesAllowed--; // reduce one mistake allowed
                     if (mistakesAllowed < 1) { // and if you have more mistakes than allowed
                         count = count + 1;
                     }
                     if (mistakesAllowed < 0) {
                         count = count - 2
                         break;
                     }
                 }
             }
             console.log('final count: ' + count);
             return count;
         }

     });

What Adeneo said: 阿德尼奥说:

 var count; //here it's defined.
 $('#btn1').click(function () {
     count = checkAnswer($('#answer1').data('correctanswer'), $('#answer1').val());
     $('#result').append('result: ').append(count); 
 }); // end of click
 $('#btn2').click(function () {
     count = checkAnswer($('#answer2').data('correctanswer'), $('#answer2').val());
     $('#result').append('result: ').append(count); 
 }); // end of click

Your function checkAnswer returns a value called count . 您的函数checkAnswer返回一个称为count的值。 That value can be assigned to the variable count . 该值可以分配给变量count

Probably the chain of thought you had was that assigning count in the function checkAnswer would also assign it to the variable count outside the function. 您可能的想法是,在函数checkAnswer中分配count也会将其分配给函数外部的变量count However those two variables are in two different scopes and are not connected to eachother unless you assign the result of the function to the variable count outside the function. 但是,除非您将函数的结果分配给函数外部的变量count否则这两个变量在两个不同的scopes并且不会相互连接。

To be more precise : 更准确地说

checkAnswer is in the same scope as the first count variable. checkAnswer与第一个count变量在同一范围内。 That means you could do this: 这意味着您可以执行以下操作:

var count = 0;
console.log(count); //will log 0.
function checkAnswer()
{
   count = 1;
}
checkAnswer();
console.log(count); //will log 1.

However when you use the operator var inside a function it will create a variable that is bound to the scope of the function (it becomes a private variable) only accessible within that function. 但是,当您在函数内部使用operator var ,它将创建一个变量,该变量绑定到该函数的作用域(它成为私有变量),该变量只能在该函数内访问。 Unless you return it to a variable outside the scope of that function. 除非您将其返回到该函数范围之外的变量。

var count = 0;
console.log(count); //will log 0.
function checkAnswer()
{
   var count = 1;
}
checkAnswer();
console.log(count); //will log 0. 

More on scopes on Stack Overflow: 有关堆栈溢出的更多信息:

What is the scope of variables in JavaScript? JavaScript中变量的范围是什么?

Bonus : 奖励

A little efficiency suggestion for your code 关于您的代码的一些效率建议

 var count;
 $('#btn1', '#btn2').click(function () {
     var buttonId = $(this).attr("id").substr(4); //will result in 1 or 2
     count = checkAnswer($('#answer' + buttonId ).data('correctanswer'), $('#answer' + buttonId ).val());
     $('#result').append('result: ').append(count); 
 }); // end of click

This will reduce it to one generic function. 这会将其简化为一个通用函数。 So when you need to update your code you only need to update one function, not multiple instances of the same code. 因此,当您需要更新代码时,只需更新一个功能,而无需更新同一代码的多个实例。

Instead of 代替

 checkAnswer($('#answer2').data('correctanswer'), $('#answer2').val());

use 采用

var count=checkAnswer($('#answer2').data('correctanswer'), $('#answer2').val()); //Stored returned value to count variable.

Now you can access returned value. 现在,您可以访问返回的值。

Here is your updated fiddle. 是您更新的小提琴。

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

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