警报最高编号

时间:2017-03-16 16:34:37

标签: javascript alert

我制作了一个用户必须回答五个问题的程序。当用户键入某个答案时,分数将添加到匹配的类别。这是我编写的代码的一部分(有一点帮助,我没有经验):

var orientaal = 0;
var houtig = 0;
var bloemig = 0;
var aromatisch = 0;
var chypre = 0;
var citrus = 0;

var q1 = prompt('Welk element spreekt jou het meest aan? Zet de letters van hoog naar laag (bijv. DBAC). \n\n A. Vuur \n B. Lucht \n C. Aarde \n D. Water')

switch(q1[0]) {
  case 'A':
  case 'a':
    orientaal += 3;
    break;
  case 'B':
  case 'b':
    bloemig += 3;
    break;
  case 'C':
  case 'c':
    houtig += 3;
    break;
  case 'D':
  case 'd':
    citrus += 3;
    break;
}
switch(q1[1]) {
  case 'A':
  case 'a':
    orientaal += 2;
    break;
  case 'B':
  case 'b':
    bloemig += 2;
    break;
  case 'C':
  case 'c':
    houtig += 2;
    break;
  case 'D':
  case 'd':
    citrus += 2;
    break;
} 

我想提醒得分最高的三个类别。我该怎么做?

1 个答案:

答案 0 :(得分:2)

var categories = [
  { name: 'orientaal', value: orientaal },
  { name: 'bloemig', value: bloemig },
  { name: 'houtig', value: houtig },
  { name: 'citrus', value: citrus },
  { name: 'aromatisch', value: aromatisch },
  { name: 'chypre', value: chypre }
];

//         sorting in decending order             getting the top 3
categories.sort(function(a, b) { return b.value - a.value; }).slice(0, 3);

// Returns an array of 3 objects
[
  {name: 'orientaal', value: 20},
  {name: 'bloemig', value: 19},
  {name: 'houtig', value: 15},
]