We can also use loops to run through the elements of an array. No matter the size of the array, we just need to write the statements once.
for (var a = 0; a < 5 ; a+=1) {
console.log(a);
}
/* The console will show:
0
1
2
3
4
*/
The run throught the elements of an array we'll use its length in the condition:
var students = ['Peter', 'Mary', 'Joseph', 'John', 'Charles'];
for (var a = 0; a < students.length ; a++) {
console.log(students[a]);
}
/* The console will show:
Peter
Mary
Joseph
John
Charles
*/
The for/in loop comes handy when we need to run through objects, since this kind of data type doesn't have the length property.
to initialize this loop we just need to create a variable that will represent each of the objects's properties at each iteration.
var car = {
'Year': 2018,
'Model': 'Evoke',
'Manufacturer': 'Land Rover',
'FuelType': 'Diesel'
}
for (var prop in car) {
console.log( prop + ': ' + car[prop] );
}
/* The console will show:
Year: 2018
Model: Evoke
Manufacturer: Land Rover
FuelType: Diesel
*/
<div class="example">Element 1</div>
<div class="example">Element 2</div>
<div class="example">Element 3</div>
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a+=1) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}
var elements = document.getElementsByClassName("example");
for (var a = 0; a < elements.length ; a++) {
elements[a].style.color = "orange";
elements[a].style['font-weight'] = "bold";
}
The incremental operator(增值) can also be written like: a++.