How to create and use an Array ?
Array are like lists, you can list and modify the array. The length of an array may vary. There are many ways to create an Array in Javascript.
let arr = new Array(); // An array has been created by 'new Array'
let arr = []; // An array has been created by [ ]
But it is not necessary to use the first method, Create an Array like this : put the string under quotes,
let colors = ['Green'];
console.log(colors);
// Green
console.log(colors.length)
// 1
Don’t forget to verify if everything is ok, with console.log() Access (via index) an array element
// Red
Add an element at the start of your table :
let newColors = colors.unshift('Red');
// ['Red','Green'];
Add an element at the end of your array :
let newColors = colors.push('Blue');
// ['Red','Green','Blue'];
Find an element in your array by his index :
let posGreen = colors.indexOf('Green');
console.log(posGreen);
// 1
Then remove it by his index :
let removedGreen = colors.splice(posGreen, 1);
// Delete an element from posGreen;
console.log(colors);
// ['Red', 'Blue'];
Delete the first element of your array :
let firstElement = colors.shift();
// 'Red' has been deleted
console.log(colors);
/ ['Green','Blue'];
Delete the last element of your array :
let lastElement = colors.pop();
// 'Blue' has been deleted
console.log(colors);
// Green
Copy an array :
let copyArray = colors.slice();
console.log(copyArray);
// Green
How to acceed to an element of an array :
let array = ['Green','Blue','Red','Black','Yellow','Brown','White'];
console.log(array[0]);// Show the first element of the array
// Green
console.log(array[1]); // Show the second element of the array
// Blue
console.log(array[4]); // Show the 5th element of the array
// Yellow
console.log(array[array.length - 1]); // Show the last element of the array