Answers for "vanilla js loop through array"

32

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
})
Posted by: Guest on December-18-2020
6

For-each over an array in JavaScript

/** 1. Use forEach and related */
var a = ["a", "b", "c"];
a.forEach(function(entry) {
    console.log(entry);
});

/** 2. Use a simple for loop */
var index;
var a = ["a", "b", "c"];
for (index = 0; index < a.length; ++index) {
    console.log(a[index]);
}

/**3. Use for-in correctly*/
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
    if (a.hasOwnProperty(key)  &&        // These checks are
        /^0$|^[1-9]\d*$/.test(key) &&    // explained
        key <= 4294967294                // below
        ) {
        console.log(a[key]);
    }
}

/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
const a = ["a", "b", "c"];
for (const val of a) {
    console.log(val);
}

/** 5. Use an iterator explicitly (ES2015+) */
const a = ["a", "b", "c"];
const it = a.values();
let entry;
while (!(entry = it.next()).done) {
    console.log(entry.value);
}
Posted by: Guest on November-27-2019
12

javascript loop through array

var myStringArray = ["hey","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}
Posted by: Guest on September-05-2019

Code answers related to "Javascript"

Browse Popular Code Answers by Language