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 is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Shuffle / Randomize Array in JavaScript

Last accessed pages

  1. PHP Unzipper - Extract Zip, Rar Archives (32244)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141748)
  3. Add, Change, and Remove Attributes with jQuery (46356)
  4. Node.js Move and Copy file (28419)
  5. Rectangle, Oval, Polygon - Star (3322)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (472)
  2. CSS cursor property - Custom Cursors (78)
  3. The Mastery of Love (69)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)