javascript loop through data to make array code example
Example 1: javascript loop through array
var data = [1, 2, 3, 4, 5, 6];
// traditional for loop
for(let i=0; i<=data.length; i++) {
console.log(data[i]) // 1 2 3 4 5 6
}
// using for...of
for(let i of data) {
console.log(i) // 1 2 3 4 5 6
}
// using for...in
for(let i in data) {
console.log(i) // Prints indices for array elements
console.log(data[i]) // 1 2 3 4 5 6
}
// using forEach
data.forEach((i) => {
console.log(i) // 1 2 3 4 5 6
})
// NOTE -> forEach method is about 95% slower than the traditional for loop
// using map
data.map((i) => {
console.log(i) // 1 2 3 4 5 6
})
Example 2: 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
});