Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JavaScript For Each Loop [duplicate]

Tags:

javascript

Okay, take it easy on me. I am really new to JavaScript and having issues getting the for-each loop to work correctly. Any Tips?

var array = ["Bob", "Nancy", "Jessie", "Frank"]; var arrayLength = myStringArray.length;  for (var i = 0; i < arrayLength; i++) {     document.write(array); } 
like image 943
ChaseHardin Avatar asked Jun 10 '14 19:06

ChaseHardin


People also ask

Does forEach create a copy?

foreach will copy the array structure if and only if the iterated array is not referenced and has a refcount > 1.

Is there for each loop in JavaScript?

The JavaScript forEach method is one of the several ways to loop through arrays. Each method has different features, and it is up to you, depending on what you're doing, to decide which one to use.

Can JavaScript set have duplicate values?

The Set object lets you store unique values of any type, whether primitive values or object references. you are passing new object not reference so it is allowing to add duplicate.


2 Answers

var myArray = ["Bob", "Nancy", "Jessie", "Frank"]; var arrayLength = myStringArray.length;  for (var i = 0; i < arrayLength; i++) {     //Do something with element myArray[i] } 

I guess you need something like this.

Edit: Your array has only 4 elements. In the 2nd line I save the length of your array (4 elements --> length is 4) in the variable 'arrayLength'. Then I wrote a simple for-loop which cycles the 'i' from 0 till 3 so you can access your elements from your array as 'myArray[i]'.

like image 114
Michel Michels Avatar answered Oct 13 '22 09:10

Michel Michels


The for in is used to iterate over properties on the object. It is not the same as a regular foreach. Use a for loop for this

like image 34
TGH Avatar answered Oct 13 '22 10:10

TGH