0

I have a quiz on my website and use local storage to save the last scores.

I like to print them in an alert and it works well, but I like to print every score in a new line.
How is this possible?

Also, is it possible to put a title (or a text above the scores) in the alert?

function highscore() {
    var lastscores = localStorage.getItem("lastscores.sort().reverse()").split("\n")
}

Example of an alert

JustCarty
  • 3,839
  • 5
  • 31
  • 51
TechGuy01
  • 29
  • 1
  • 11

4 Answers4

2

You should use the join function instead of split for instance:

const scores = [1,2,3]; 

alert(scores.join("\n"))
Ali Torki
  • 1,929
  • 16
  • 26
  • 1
    Like this: function highscore() { var lastscores = localStorage.getItem("lastscores.sort().reverse()").join("\n"); } It is the same result :( – TechGuy01 Oct 17 '18 at 10:15
2

Try this

alert(scores.toLocaleString().replace(/,/g, '\n'))
MBehtemam
  • 7,865
  • 15
  • 66
  • 108
0

Try this code:

function highscore() {
var lastscores = localStorage.getItem("lastscores.sort().reverse()").replace(/ *, */g, '<br>');
}
0

in this code, I first save some score in an array, then retrieve it from localStorage and then split it to array, because it's string so parse it to integer and then sort it in descending order. if you want ascending order to replace b-a to a-b

  localStorage.setItem("lastscores",[18,44,5,7]);
  var title = "Your HighSocres";

function highscore() {
  var lastscores =   
  localStorage.getItem("lastscores")
              .split(',')
              .map(function(s){
                      return parseInt(s); //convert to integer(Number)
                 })
              .sort(function(a,b){
                      return b -a //sort decending)
                    })
             .join('\n')
var toAlert = title + "\n" + lastscores
    alert(toAlert)
}

for title you can do something like :

const allString = "Your socres \n" + lastscores
MBehtemam
  • 7,865
  • 15
  • 66
  • 108