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. Pencil and Pen Tools (2262)
  2. Graphic Symbols (1512)
  3. CSS cursor property - Custom Cursors (6184)
  4. Responses (329)
  5. Add sounds and audio effects in Flash (3540)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)