Answers for "javascript loop through arrays"

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
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
0

javascript loop through array

array iteration styles illustrate programming paradigms
let newArray = [];  const theArray = [2, 4, 6, 8, 10]
// 1) imperative, explicit
for (var i = 0; i < theArray.length; i++) {  // var is mutable
    console.log(theArray[i]);                // side effect from writing to console
	newArray[i] = theArray[i] * theArray[i]  // let is mutable
}
// 2) forEach function of the Array class TIP: console.log(Array) //Does not change the array, Returns undefined
function f1(theValue, theIndex, originalArray) { numVal = numVal *  theValue }
theArray.forEach(f1);   console.log( ` creates  ${   newArray   }` );
run.addEventListener("click", function () {cpeople.forEach((element) => console.log(element.firstname));});
// 3) declarative, implicit 
function f1(v,i,a) { v=v*v }
const constArray = theArray.map(fNumbers); 
console.log( ` immutable  ${ newArray }` );
Posted by: Guest on November-19-2020

Code answers related to "javascript loop through arrays"

Code answers related to "Javascript"

Browse Popular Code Answers by Language