Javascript Course

The function presented bellow can be used to shuffle /randomize array items in JavaScript.


Script code

// receive an array and return it with the items shuffled /randomized
function shuffle(ar){
 for(var j, x, i = ar.length; i; j = Math.floor(Math.random() * i), x = ar[--i], ar[i] = ar[j], ar[j] = x);
 return ar;
}
- Here is a simple example:
<h4>Example shuffle array in JavaScript</h4>
<p>Initial array: ar1 = ['a', 'b', 'c', 1, 2, 3];</p>

<button id='btntst'>Test Shuffle Array</button>
<script>
// receive an array and return it with the items shuffled /randomized
function shuffle(ar){
 for(var j, x, i = ar.length; i; j = Math.floor(Math.random() * i), x = ar[--i], ar[i] = ar[j], ar[j] = x);
 return ar;
}

var ar1 = ['a', 'b', 'c', 1, 2, 3];

//when click on the #btntst, show alert box with the items of ar1
document.getElementById('btntst').addEventListener('click', function(){
 ar1 = shuffle(ar1);
 alert(ar1);
});
</script>
Demo:
Initial array: ar1 = ['a', 'b', 'c', 1, 2, 3];

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Shuffle / Randomize Array in JavaScript

Last accessed pages

  1. Select the Content of HTML Element (4444)
  2. Zodiac Signs JavaScript code (10965)
  3. The Four Agreements (1508)
  4. Prayer The Art of Believing (1583)
  5. Node.js Move and Copy file (28189)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (315)
  2. PHP Unzipper - Extract Zip, Rar Archives (107)
  3. Read Excel file data in PHP - PhpExcelReader (100)
  4. SHA1 Encrypt data in JavaScript (81)
  5. Get and Modify content of an Iframe (73)
Chat
Chat or leave a message for the other users
Full screenInchide