简体   繁体   中英

Java Script. How to choose any few items of array

I'm designing a quiz motivator, ie if a user inputs any number of correct answers he's gonna get rewarded with a "star" or smth. The array in a pseudo code below represents a range of correct answers to choose from:

 var rightAnswers = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; if (rightAnswers.chooseAny(3)) {user gets a star} else if (rightAnswers.chooseAny(6)) {user gets 2 stars} else if (rightAnswers.chooseAny(9) {user gets 3 stars} 

I haven't found anything that would work instead of my pseudo "chooseAny()", any ideas, please?

You probably aren't looking for a chooseAny function; I think what you're really asking for is a way to count how many answers were correct given a set of answers and an answerKey .

The getTotalCorrect function below does that for you using a for-loop and identity comparison, and you can use getStars to determine how many stars should be awarded based on the score that is returned.

 var answerKey = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] function getTotalCorrect (answers, answerKey) { for (var correct = 0, i = 0; i < answerKey.length; i++) { if (answers[i] === answerKey[i]) correct++ } return correct } function getStars (totalCorrect) { return (totalCorrect / 3) | 0 } var totalCorrect = getTotalCorrect(['a', 'a', 'c', 'c', 'e', 'e', 'e'], answerKey) console.log(totalCorrect) //=> 3 var stars = getStars(totalCorrect) console.log(stars) //=> 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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