Answers for "iterating in javascript"

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
1

js loop through array

// ES6 for-of statement
for (const color of colors){
    console.log(color);
}

// Array.prototype.forEach
const array = ["one", "two", "three"]
array.forEach(function (item, index) {
  console.log(item, index);
});

// Sequential for loop
for (var i = 0; i < arrayLength; i++) {
    console.log(myStringArray[i]);
    //Do something
}
Posted by: Guest on July-27-2020
3

iterators in javascript

//Iterators
function fruitsIterator(array) {
  let nextIndex = 0;
  //fruitsIterator will return an object
  return {
    next: function () {
      if (nextIndex < array.length) {
        //next function will return the below object
        return {
          value: array[nextIndex++],
          done: false,
        };
      } else {
        return { done: true };
      }
    },
  };
}
let myArr = ["apple", "banana", "orange", "grapes"];
console.log("My array is", myArr);

//using the iterator 
const fruits=fruitsIterator(myArr);
console.log(fruits.next()); //apple
console.log(fruits.next());//banana
console.log(fruits.next());//grapes
Posted by: Guest on May-12-2021
4

for loop javascript

var i;
for (i = 0; i < 10 ; i++) {
  //do something
}
Posted by: Guest on July-30-2020
2

what is an iterator in javascript

The iterator is an object that returns values via its method next()
Posted by: Guest on July-02-2020

Code answers related to "iterating in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language