尝试使函数查找数组是否具有比另一个数组更多的值

时间:2019-02-09 03:43:29

标签: javascript

我正在一个简单的项目中,向用户提出问题,并将他们的答案记录在一个数组中(值为0表示是,值为1表示否)。我只是一个初学者,所以请解释一下您发送给我的代码。

我什么都没尝试,但是我认为最好的方法是创建一个函数,如果数组的值大于0,则它应该显示测试的某个结果,如果它等于零,它应该显示不同的结果(我不知道如何实现这一点。)

questionOneInputYes.addEventListener("click", function() {
    if (questionTwo.style.display="none") {
        questionTwo.style.display="block";
        answerData.push(0);
    }
})

questionOneInputNo.addEventListener("click", function() {
    if (questionTwo.style.display="none") {
        questionTwo.style.display="block";
        answerData.push(1);
    }
})

4 个答案:

答案 0 :(得分:1)

我建议不要使用带有两个键的dictionary:不使用数组,不使用数组。因此,与其创建一个由零组成的数组,不如创建一个字典。例如:

let answers = {
  'yes': 0,
  'no': 0
}

然后,您可以根据点击的按钮来增加yesno

questionOneInputYes.addEventListener("click", function() {
    if (questionTwo.style.display="none") {
        questionTwo.style.display="block";
        answers['yes'] +=1;
    }
})

这样做的好处是它是一个更有意义的数据结构(不仅是1和0的数组),而且您已经可以访问总数而无需进行任何其他计算,因此检查是否还有更多的数据很简单。是或否答案:

answers['yes'] > answers['no']

答案 1 :(得分:0)

假设您在测验末尾有一个answerData,看起来像:

[1, 1, 0, 0, 1, 0, 1, 1]

您现在可以使用Array.prototype.reduce()

const answerData = [1, 1, 0, 0, 1, 0, 1, 1];
const noTot = answerData.reduce((acc, curr)=> acc + curr) ;

console.log( noTot ) // 5

如果没有回答,您将得到5作为结果


停止重复自己!编程并不是要复制粘贴代码(就像在您的示例中一样,每个问题都有自己专用的稍微重命名的复制粘贴的侦听器和处理函数...)。

相反,创建一个counter来跟踪进度,您只需要两个按钮和一个DIV即可解决问题:

const elQ   = document.querySelector("#question"); // Cache elements
const elBtn = document.querySelectorAll(".answer");

const QA = [ // Array of Objects ("a:" answers will be populated during the quiz)
  {q:"Do you like coding?"},
  {q:"Are you tall?"},
  {q:"Are you hungry?"},
  {q:"Are you thirsty?"},
]; 

let c = 0; // Start counter at index 0 (first QA question)
const askQuestion = () => elQ.textContent = QA[c].q;          // Show question
const setAnswer = (btn) => QA[c].a = parseInt(btn.value, 10); // Populate with answer
const showResult = () => {
  console.log(QA);
  Array.from(elBtn).forEach(el => el.disabled = true);        // Disable buttons
  const nopes = QA.reduce((acc, curr) => acc + curr.a, 0);    // Total of NO answers
  elQ.innerHTML = `
    Tot questions: ${QA.length}<br>
    Yes answers: ${QA.length - nopes}<br>
    No answers: ${nopes}
  `;
};
const handleAnswer = (ev) => {
  setAnswer(ev.target);
  if(c === QA.length-1 ) return showResult();
  c++;
  askQuestion();
};

// Events
Array.from(elBtn).forEach(el => el.addEventListener('click', handleAnswer));
// Start!
askQuestion();
<div id="question"></div>
<button class="answer" type="button" value="0">YES</button>
<button class="answer" type="button" value="1">NO</button>

答案 2 :(得分:0)

如果您要做的只是查看数组中的零是否大于1,反之亦然,则可以将数组中的所有1过滤到另一个数组中,并获取长度包含那些的数组。在这里,我使用了.filter(Boolean),它将为您提供一个数组。这之所以有效,是因为javascript中的1是“真实的”。 (这相当于执行.filter(n => n===1)

接下来,您可以使用.filter(n => !n)将所有零添加到数组中。之所以可行,是因为零是“容易的”,因此!false将为true,从而使您可以保留所有零。 (这等效于进行.filter(n => n===0)

因此,通过获取两个数组的长度,您可以检查哪个数组中包含更多元素,然后使用if语句进行相应输出。

请参见以下示例:

const arr = [1, 1, 1, 0, 0],
ones = arr.filter(Boolean).length, // gives length of [1, 1, 1] (3)
zeros = arr.filter(n=>!n).length; // gives length of [0, 0] (2)

console.log(ones, zeros);
if(ones > zeros) {
  console.log("There are more ones in the array than zeros")
} else if(ones < zeros){
  console.log("There are more zeros in the array than ones");
} else {
  console.log("The same amount is in both");
}

注意::如果您事先知道问题的数量,那么zeros将等于numberOfQuestions - ones,从而提高代码的效率。

答案 3 :(得分:0)

如果您有很多问题,像上面这样硬编码可能会很麻烦。您可以创建一系列问题并将其循环以生成html。请阅读代码,如有疑问,请询问。

var container = document.querySelector(".questionContainer");

var questions = ["Hello?","World?","Foo?","Bar?"]; // add more questions to the array as required 

var answerData = [];

/* Read on Array.prototype.reduce and Arrow Operators on MDN. 
Basically it runs a for loop in the array and updates a temporary variable with some value */

var questionHTML = questions.reduce((_html,question,index) => {
  /*
  For each question, it creates and appends the above HTML code to the 
  container. For first question, set display to block and set display 
  none for all other question. This will be modified when someone
  submits an answer. We are using the same submitAnswer function in 
  both buttons and changing the value based on YES/NO. ${} is used to
  put the value from a variable in template strings.
  */
  _html += `<div id="q-${index}" style=" display:${index===0? 'block' : 'none'}"><p> ${question} <\p>
  <button onclick="submitAnswer(0,${index})"}>NO</button>
  <button onclick="submitAnswer(1,${index})">YES</button>
  </div>
  `
  return _html;  

} ,"");

function submitAnswer(value, index) {
  // add the value of YES/NO according to button into the answer array at the specified index
  answerData[index] = value; 
  // console.log(answerData);
  if(index < questions.length - 1){ // for all questions except the last question, -1 since the numbers are from 0...length-1 for an array , we select the currentQuestion and nextQuestion with the id we had assigned to the div during the html creation using reduce as above. Then we set current question to display none and next question to display block.

  currQuestion = document.querySelector(`#q-${index}`);
  nextQuestion = document.querySelector(`#q-${index+1}`);
  currQuestion.style.display = "none";
  nextQuestion.style.display = "block";
 } else {
  // after all questions are completed, show finished.
  container.innerHTML = "<p>You have finished the quiz</p> answers : "+ answerData.join(',')
   // do something with the answerData array
 }
  
}

container.innerHTML = questionHTML;
<div class="questionContainer">
</div>