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 adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
Shuffle / Randomize Array in JavaScript

Last accessed pages

  1. Delete multiple consecutive characters and Split long words (645)
  2. Mysql SELECT JOIN tables on two different Databases (4322)
  3. JpGraph - Create Graph, Charts, Plots in PHP (3803)
  4. PHP-MySQL Tutorials (4202)
  5. Useful PHP Classes (3518)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (294)
  2. Read Excel file data in PHP - PhpExcelReader (100)
  3. The Four Agreements (89)
  4. PHP Unzipper - Extract Zip, Rar Archives (86)
  5. The Mastery of Love (83)
Chat
Chat or leave a message for the other users
Full screenInchide