【问题标题】:Updating Array comparison function for strings更新字符串的数组比较函数
【发布时间】:2017-08-14 14:31:22
【问题描述】:

我正在使用预先编写的问答问答游戏代码,我必须将游戏问题选择从数值更新为字符串。但我不完全知道要对用户选择的代码进行哪些更改以与正确答案进行比较。目前,对于数字答案,代码将选择数组中正确选项的数组位置与正确答案变量进行比较。我最好的猜测是更改必须发生在底部显示的 displayScore 函数中。

当前问题对象:

        {
            question: "What is 2*5?",
            choices: [2, 5, 10, 15, 20],
            correctAnswer: 2
        }

更新后的问题对象将是:

        {
             question: "Which list contains words that are NOT names of shoe types:"
             choices:[   "A. Oxford, jelly, boat, clogs, stiletto, mary jane",
                         "B. Loafer, gladiator, wedge, mule, platform",
                         "C. Pump, moccasin, wingtip, sneaker, derby, monk",
                         "D. Chalupa, dogler, hamster, croonley, frankfurt"],
             correctAnswer : "D. Chalupa, dogler, hamster, croonley, frankfurt"
        }

目前计算正确答案的部分代码是:

//Array containing user choices
var selections = []; 

// Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }

// Computes score and returns a paragraph element to be displayed
  function displayScore() {
    var score = $('<p>',{id: 'question'});

    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
      }
    }
  } 

【问题讨论】:

  • correctAnswer 指的是choices 中的密钥。坦率地说,我认为处理正确答案的原始方式更加通用。
  • 选择一个对象数组。然后你可以拆分键/描述,例如。 [{ 'A', 'Oxford, jelly, boat, clogs, stiletto, mary jane' },{ 'B', ... }]。然后你可以简单地对照正确的键检查答案
  • 您为什么不简单地将correctAnswer 保留为索引(在您的示例中:3)?它适用于字符串数组以及数字数组。
  • 只需删除 + ...

标签: javascript jquery arrays compare


【解决方案1】:

学分:

正如 cmets 中的 Jonas w 所提到的,问题在于 $().val() 之前的 +。因为它没有得到任何赞成或解释,我想我会详细说明:

错误

从输入中检索值时,该值始终为string。您最初示例中的正确答案是number。因为你用===比较,两者不相等:2 === "2"返回false

添加+ 运算符是将值“转换”为数字的一种简短方法。 (意见:)很多人不喜欢它,因为它很容易被初学者忽略并且难以解释。也许更清晰的方法是写Number(x) 或使用parseIntparseFloat

问题是,一旦您需要的值为string+ 运算符将尝试从非数字字符串中生成一个数字。结果将是,很好命名的NaN,它代表Not a Number,可以使用isNaN进行检查

即: 作品:

const required = 2;
const input = "2";
required === +input; // 2 === 2 -> true

休息:

const required = "Hello world";
const input = "Hello world";
required === +input; // "Hello world" === NaN -> false

如何解决

结论:删除+修复基于字符串的答案,但破坏基于数字的答案。

我的建议是删除 +,但请确保您的答案数组包含字符串。 (例如,通过使用[2, 3, 4].map(String)toString 进行映射)

其他可能的修复包括:

  • displayScore 中使用== 运算符将用户输入与所需值进行比较(推荐)
  • 为数组值的类型添加 switch 语句,以便为 numberstring 以及可能的其他值选择自定义比较方法。
  • 按照用户 Bergi 的建议,在数组中使用 index 而不是值(尽管可能会使 question 对象更难阅读)

示例

一些可以帮助您了解值之间差异的示例:

var val = $("input").val();

console.log("typeof val ->", typeof val);
console.log("typeof 2 ->", typeof 2);
console.log("val == 2 ->", val == 2);
console.log("val === 2 ->", val === 2);
console.log("+val === 2 ->", +val === 2);
console.log("Number('2') === 2 ->", Number(val) === 2);

var nonNumericString = "Hello world";
console.log("+'Hello world' ->", +nonNumericString);

var answers = [2, 3, 4];
console.log("'2' in [2, 3, 4] ->", answers.includes(val));
console.log("'2' in [2, 3, 4].map(String) ->", answers.map(String).includes(val));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="2">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多