The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.
AKA a data type that stores a lot of items in the same variables (as a big box).
Why Array
Assume you have a series of data to store
1,4,67,54,32,75
And without array, you would store the values like this:
let numberOne =1;let numberTwo =4;let numberThree =67let numberFour =54// Bad method ...
Instead of create a series of variables, we would store those data in a single boxes (array)
// Good method to store the series datalet numberArray = [1,4,67,54,32,75];
We can easily sum up those data with array method.
// Bad method to sumlet numberOne =1;let numberTwo =4;let numberThree =67;let numberFour =54;let sum = numberOne + numberTwo + numberThree + numberFour;
// Good method to sumlet numberArray = [1,4,67,54];let sum =0;for(let val of numberArray){ sum += val}
We can adjust the array in code instead of declare a new variable.
let numberArray = [1,4,67,54];numberArray.push(100); // Add 100 to the numberArrayconsole.log(numberArray) // 1, 4, 67, 54, 100
let numberArray = [1,4,67,54];numberArray.pop(); // Remove the last item in numberArrayconsole.log(numberArray) // 1, 4, 67
Array Rules One
In general, array can be store various item with same type
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {// code block to be executed}
Expression 1 is executed (one time) before the execution of the code block. Expression 2 defines the condition for executing the code block. Expression 3 is executed (every time) after the code block has been executed.
For loop with index
for (let i =0; i <5; i++) {console.log(i)}
Expression 1 : let i = 0 (Initial values) Init a variable call iExpression 2 : i < 5 (Conditions) The loops will continus if this conditions is true Expression 3 : i++ (After a loop occur)
For loop with index
for (let i =0; i <5; i++) {console.log(i)}// 0// 1// 2// 3// 4
For loop with index (array)
let arr = [1,2,3,4,5,6,7]for (let i =0; i <arr.length; i++) {console.log("Hello: "+ arr[i]);}
Expression 1 : let i = 0 (Initial values) Expression 2 : i < arr.length (Conditions) Expression 3 : i++ (After a loop occur)
In javascript, instead of using index, we can use for of loop to loop through elements directly.
let arr = [1,2,66,4]for (let val of arr) {console.log(val);}// 1// 2// 66// 4
of loop can loop the array without the index
let nameArr = ["hello","yolo","tom"]for (let v of nameArr) {console.log(v);}// "hello"// "yolo"// "tom"
Javascript for/in
in loop will have you to loop the array with the index, but do not need to init the index variables
let nameArr = ["hello","yolo","tom"]for (let ind in nameArr) {console.log(ind);}// 0// 1// 2
in loop can get the array element with arr[i] also, but we do NOT recommended to use for in to loop the array in general situations.
let nameArr = ["hello","yolo","tom"]for (let ind in nameArr) {console.log(nameArr[ind]);}// "hello"// "yolo"// "tom"
The in loop are powerful in looping the object that we will cover in pages later.
Javascript while
while loop is a loop logics which mainly use on looping thats We do not know how many times will the looping occur. Means in most of the time, we will use for/of / for/in or index for to loop a array.
while(<conditions>){// do stuff}while(true){console.log("Hello")}
while loop a array
let nameArr = ["hello","yolo","tom"]let i =0;while(i <nameArr.length){console.log(nameArr[i]) i++;}
Javascript do while
It is the same as the while logics, but it will run the inside code ONCE no matter the while loops is true or false at first.
do{// do something} while(<conditions>)do{// do something} while(true)
while Samples
while(false){console.log("Hello")}//
Hello will NOT printed
do while Samples
do{console.log("Hello")} while(false)// Hello
Hello will print once even the while(false)
Continue and break
In both for and while loop, if we want to skip a certain conditions or break the loop, we may use continue and break to achieve the situations.
while(true){break;}while(true){continue;}for(let i =0; i <6; i ++){continue;}
continue
when a continue occur, it will skip the current loop block.
for(let i =0; i <6; i ++){if(i %2===0){continue; // skip the current loop }console.log(i)}// 1// 3// 5
break
when a break occur, it will skip WHOLE loop block.
for(let i =0; i <6; i ++){if(i ===3){break; // escape the current loop }console.log(i)}// 0// 1// 2
Object
The Object type represents one of JavaScript's data types. It is used to store various keyed collections and more complex entities.
AKA we want to pack some variables together as a objects.
Assume we have a person data
let names ="tom"let ages =34let gender ="F"let hobby = ["coding","running"]
Instead of split up those variables, we tend to create a object for this.
let people = { names :"tom", ages :34, gender :"F", hobby : ["coding","running"]}
We can access the object like this:
let people = { names :"tom", ages :34, gender :"F", hobby : ["coding","running"]}// Access the peopleconsole.log(people.name) // tomconsole.log(people.hobby) // ["coding", "running"]// Alternative method to accessconsole.log(people["name"]) // tomconsole.log(people["hobby"]) // ["coding", "running"]
We tend to use object for a series of variables for functions reuse.
functionprintPeople(ppl){console.log("Hello this is "+ppl.names);console.log("I am age of "+ppl.ages);}printPeople(peopleOne)// "Hello this is tom"// "I am age of 34"printPeople(peopleTwo)// "Hello this is jason"// "I am age of 21"
In general, we have these functions to get the regarding elements. Both functions are built in for web.
// getElementByconstmsgBox=document.getElementById('msg');constyoloBox=document.getElementsByClassName("yolo"); // Is a array
// querySelectorconstmsgBoxQu=document.querySelector('#msg');constyoloBoxQu=document.querySelector(".yolo"); // Not a array// Since msg is a id, so we need to add #// Since yolo is a class, so we need to add .
Those function can help us to get the regarding elements.
Add interactions to boxes
In general, we can add events to the DOM elements:
constmsgBox=document.getElementById('msg');// When the msgBox box clicked, a message box will be pop up msgBox.addEventListener("click",function() {alert("Hello mate")});
index.html
<!DOCTYPEhtml><htmllang="en"><head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <h3id="msg">Hello mate</h3> <h3class="yolo">yolo hi</h3> <script>constmsgBox=document.getElementById('msg');// When the msgBox box clicked, a message box will be pop up msgBox.addEventListener("click",function() {alert("Hello mate") }); </script></body></html>
Advance control
You can control the message of the elements by innerHTML too.
<!DOCTYPEhtml><htmllang="en"><head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <h3id="msg">Hello mate</h3> <h3class="yolo">yolo hi</h3> <script>constmsgBox=document.getElementById('msg');constyoloBox=document.getElementsByClassName("yolo");// When the msgBox box clicked, a message box will be pop up msgBox.addEventListener("click",function() { yoloBox[0].innerHTML ="hello ar" }); </script></body></html>