Javascript Local Storage get item and set item

Description

Javascript Local Storage get item and set item

View in separate window

<!DOCTYPE html> 
<html lang="en"> 
<body> 
    <p id="demo"></p>
    <script> 
        let ads = [ //  w  ww  .  j  ava  2 s .  c om
            "Message 1", 
            "message 2", 
            "message 3" 
        ]; 
        function getRandomNumber(min, max) { 
            return Math.floor((Math.random() * max) + min); 
        } 

        let lastAdNumber = localStorage.getItem("lastAdNumber"); 
        let nextNumber = getRandomNumber(0, ads.length); 

        if (lastAdNumber == null) { 
            lastAdNumber = nextNumber; 
        } else { 
            lastAdNumber = parseInt(lastAdNumber, 10); 
            while (lastAdNumber == nextNumber) { 
                nextNumber = getRandomNumber(0, ads.length); 
            } 
        } 

        localStorage.setItem("lastAdNumber", nextNumber); 

        document.getElementById("demo").innerHTML = ads[nextNumber]; 
    </script> 
</body> 
</html> 



PreviousNext

Related