Javascript Course


Creating Arrays

The Array Object is used to store multiple values in a single variable name.
Each stored value becomes an array element, it has assigned an 'index number' (starting from 0). With this index you can refer to any element of that Array.
There are various ways to create an array:

Using the 'new' keyword

<script>
var ar_name1 = new Array('CoursesWeb', 'lessons', 5);

// or
var ar_name2 = new Array();
 ar_name2[0] = 'CoursesWeb';
 ar_name2[1] = 'lessons';
 ar_name2[2] = 5;
</script>

Using square brackets (Literal Array)

<script>
var ar_name3 =['tutorials', 'programming', 78];

// or
var ar_name4 =[];
 ar_name4[0] = 'tutorials';
 ar_name4[1] = 'programming';
 ar_name4[2] = 78;
</script>

Accessing Array's elements

To access the elements of an Array, you use an 'index number' that provides access to each element of the array by its position in the array.
The syntax to assign the first element of an array to a variable is the following:

var variable_name = array_name[0];
- array_name is the name of the Array.
- The 0 in brackets is the index number for the first element of the array, the second has an index number of 1, the third has an index number of 2, and so on.

Example, writes in page the second item of an array:
var sites = ['coursesweb.net', 'marplo.net', 'gamv.eu'];
var a_site = sites[1];
var other_site = sites[2];
document.write('<p>'+a_site+'</p>'); // marplo.net

Add and Modify Items in Array

After you have created an array, you can add new elements or modify existing items in that array.
To add or modify a value in an array, assign a new value to the element with a specified index number.

- Syntax:
array_name[index] = 'new value';

To add new elements to the end of an array, use the push() method.
- Syntax:
var array_name =['v1'];
array_name.push('v2', 'v3');

To get the numbers of items in an Array, apply the length property.
You can get the index of the last element in Array with this code: (array.length -1).

- Example, on an array with two items, it is modified the value of the second item (index 1), and adds a new element at the end:
//array with 2 elements
let arr =['HTML', 'PHP'];

//modify the second element
arr[1] ='Tutorial JS';

//adds a new item after the last element
arr.push('New item');

//test, arr has 3 items
document.write('<br>arr has '+ arr.length +' elements. The second value is: '+ arr[1]);

Traversing the elements of an Arrays

The elements of an Array can easily be parsed with the for() instruction, or with the forEach() method.

- Example with for(), traverses and displays the value of each item of an array.
var tutorials = ['php', 'html', 'css', 'javascript'];

//writes each element of the 'tutorials' array
for(i=0; i<tutorials.length; i++) {
 document.write('<br>'+ tutorials[i]);
}
The forEach() method calls a 'callback' function for each element in the array.
- Syntax:
array.forEach(callbackF)
The 'callbackF' function has this syntax:
var callbackF =(va, index, array)=>{
 //code of the function
}
'val' is the value of current item.
'index' (optional) is the item index
'array' (optional) is the traversed array.

Example with forEach(), traverses and shows the index and value of each element in an array.
//the callback function
let parseArr =(v, i)=>{
 //writes the index and value of current item
 document.write('<br>'+ i +' - '+ arr[i]);
}

//array with 4 elements
let arr =['HTML', 'CSS', 'JavaScript', 'PHP'];

//parses the array with forEach() and the parseArr() function
arr.forEach(parseArr);

Working with array elements

JavaScript contains many methods to work with the elements of an array. A list with these methods can be found at the page from: coursesweb.net/javascript/methods-array-object-js
Here is a few examples.


- Checking whether a variable is an array. It is applied the method: Array.isArray().

let arr =['CoursesWeb.net', 'GamV.eu', 90];

//if arr is an array, shows the first element
if(Array.isArray(arr)) document.write('- First elm.: '+arr[0]);
- Sorts an Array in alphabetical order. it is applied the sort() method.
let arr =['ef', 'a8', 9, 78];
arr.sort(); //sorts in alphabetical order

console.log(arr); //[78, 9, 'a8', 'ef']
- The sum and product of elements from an array. It is applied the reduce() method with a callback function.
const arr =[1, 2, 3, 4];

//sum of the elements in arr
const ar_sum = arr.reduce((a, b)=>a+b);

//product of elements in arr
const ar_prd = arr.reduce((a, b)=>a*b);

document.write('<p>The sum of the numbers from [1, 2, 3, 4] is: '+ar_sum+'; The product: '+ar_prd+'</p>');

Multidimensional Array

The element of an array can contain any type of value, so its value can be another array.
The elements of the inner array are accessed hierarchically starting from the main array.
- Syntax:
array[index_inner_array=][index_elm]
- Example with a Bidimensional array:
<div id='dv1'>JS, Bidimensional array</div>

<script>
//defines a bidimensional array (the second item is an array)
let arr =[
 'Web develop',
 ['html', 'css', 'javascript'],
 'xyz'
];

//the index of last item in the inner array (which is at arr[1])
let ix = arr[1].length -1;

//gets the value of first item in 'arr', and the last from the inner array
let title = arr[0];
let tutor = arr[1][ix];

//adds the values in #dv1
document.getElementById('dv1').innerHTML ='<h3>'+ title +'</h3>Tutorial '+ tutor;
</script>

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
JavaScript Arrays

Last accessed pages

  1. Align DIVs on the same line (8477)
  2. CSS3 2D transforms (868)
  3. Create and Use in PHP a Simple Template Page (3306)
  4. Common PHP Errors and Solutions (9771)
  5. PHP getElementById and getElementsByTagName (49471)

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 (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)