Table of contents
Arrays - Taking the whole Team
If we are making a cricket team we will just have the team players and we won't take anyone else Similarly if we want to make an array we take similar type of data to represent.
Declaration
As the Coach, The Management gave me a list to select players for my IPL Team -> JS_SUPER_KINGS.
An empty list was given to me : To select an empty list i can do it in two ways in JavaScript.
let JS_SUPER_KINGS = []
//OR
let JS_SUPER_KINGS = new Array();
I want to keep my player as "Kohli","Dhawan","Yuvi","AB Divillers","maxwell", "MS Dhoni (c)".
let JS_SUPER_KINGS = ["Kohli","Dhawan","Yuvi","AB Divillers","maxwell", "MS Dhoni (c)"]
Now For my batting order i want to see players according to the list , batting order it starts from 0. with the help of JS i can just print the players:
console.log(JS_SUPER_KINGS[0]) // kohli will be printed
console.log(JS_SUPER_KINGS[1]) // Dhawna will be printed
console.log(JS_SUPER_KINGS[2]) // Yuvi will be printed
console.log(JS_SUPER_KINGS[3]) // AB Divillers will be printed
console.log(JS_SUPER_KINGS[4]) // Maxwell will be printed
console.log(JS_SUPER_KINGS[5]) // MS Dhoni(c) will be printed
Now i have decided to add "chahal" to the team in place of "maxwell":-
JS_SUPER_KINGS[4] = "chahal"
I am way too tired but the management asked me to print the list of player , they want to see them , for that i can just write few lines to print all the player ;
for(let i=0;i<JS_SUPER_KINGS.length;i++){
console.log(JS_SUPER_KINGS[i])
}
// it will print all the players
//kohli,dhawan,yuvi,AB Divillers,chahal,MS Dhoni(c)
Some Array Methods
The management told me to list the total number of players, i can do this by using
JS_SUPER_KINGS.length // it will give the total players - 6
The management thought that we may need more players in our arsenal , so they told me to add "Kl rahul","rishab panth" to our list.
JS_SUPER_KINGS.push("Kl rahul");
JS_SUPER_KINGS.push('rishab panth')
//our new list will be
//kohli,dhawan,yuvi,AB Divillers,chahal,MS Dhoni(c),kl rahul,rishab panth
Rishab Panth was costing too much and the management thought of dropping it , he was at the end of our list.
JS_SUPER_KINGS.pop();
//our new list will be
//kohli,dhawan,yuvi,AB Divillers,chahal,MS Dhoni(c)
Suddenly Kohli got injured , he was at the beginning of our list , we had to drop him
JS_SUPER_KINGS.shift();
//our new list will be
//dhawan,yuvi,AB Divillers,chahal,MS Dhoni(c),kl rahul,rishab panth
I thought of getting Shewag in place of kohli, and add Shewag at the beginning
JS_SUPER_KINGS.unshift("Shewag");
//our new list will be
//Shewag,dhawan,yuvi,AB Divillers,chahal,MS Dhoni(c),kl rahul,rishab panth