looping through array code example

Example 1: javascript code to loop through array

var colors = ["red","blue","green"];
for (var i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

Example 2: iterate array javascript

array = [ 1, 2, 3, 4, 5, 6 ]; 
for (index = 0; index < array.length; index++) { 
    console.log(array[index]); 
}

Example 3: loop through javascript array

let colors = ['red', 'green', 'blue'];
for (const color of colors){
    console.log(color);
}

Example 4: how to loop through array of numbers in javascript

let numbers = [1,2,3,4,5];
let numbersLength = numbers.length;
for ( let i = 0; i < numbersLength; i++) {
    console.log (numbers[i]);
}

Example 5: iterate through array js

let arbitraryArr = [1, 2, 3];
// below I choose let, but var and const can also be used 
for (let arbitraryElementName of arbitraryArr) {
  console.log(arbitraryElementName);
}

Example 6: javascript loop through array

// looping through an array in javascript using our own myEach function

// Write an `Array.prototype.myEach(callback)` method that invokes a callback
// for every element in an array and returns undefined.
Array.prototype.myEach = function(callback) {
    for (let i = 0 ; i < this.length ; i ++) {
        callback(this[i]);
    }
}

let array = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];

array.myEach(function (element) {
	console.log(element); // this will print each element in the array
    // Code to do something to each element in the array
});

Tags:

Cpp Example