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 HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Shuffle / Randomize Array in JavaScript

Last accessed pages

  1. Get and Modify content of an Iframe (32367)
  2. $_GET, $_POST and $_REQUEST Variables (33884)
  3. Ajax-PHP Chat Script (49508)
  4. JavaScript Course - Free lessons (31647)
  5. Volume and Surface Area Calculator for 3D objects (11276)

Popular pages this month

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