xxxxxxxxxx
var counter = 0;
for(var i = 0; i < 10; i++){
counter = i;
}
xxxxxxxxxx
var tops = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144];
for (let i = 0; i < tops.length; i++) {
document.write(tops[i] + "tops");
}
xxxxxxxxxx
// array
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// object
const obj = {
"property1": "value",
"property2": 1,
"property3": true
};
// for loop: for (initializer; condition; increment)
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// for in loop: for (let variable in array/object)
for (let i in arr) {
console.log(i, arr[i]);
}
for (let key in obj) {
console.log(key, obj[key]);
}
// for of loop: for (let variable of array)
for (let element of arr) {
console.log(element);
}
// forEach: element
arr.forEach(element => console.log(element));
// forEach: element, index
arr.forEach((element, i) => console.log(element, i));
// forEach: element, index, arr
arr.forEach((element, i, originalArr) => console.log(element, originalArr[i]));
// the map method of arrays is identicle to the forEach method except it creates and returns a new array
//coded by Anshul Soni
//dont forget to see who am I? on https://anshulsoni.tech
xxxxxxxxxx
For printing 0 to 9
you can write like below also
var i;
for (i = 0; i < 10; i++) {
console.log(i);
}
xxxxxxxxxx
for (i in things) {
// If things is an array, i will usually contain the array keys *not advised*
// If things is an object, i will contain the member names
// Either way, access values using: things[i]
}
xxxxxxxxxx
const numbers = [3, 4, 8, 9, 2];
for (let i = 0; i < numbers.length; i++) {
const accessNumbers = numbers[i];
console.log(accessNumbers);
}
//Expected output:3 4 8 9 2
xxxxxxxxxx
for( initialization of expression; condition; action for initialized expression ) {
instruction statement to be executed;
}