In Java, you can use a for
loop to traverse objects in an array as follows:
String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
// Do something
}
Can I do the same in JavaScript?
The formal (and perhaps old) way is Array.prototype.forEach(...)
:
var arr = ["apple", "banana", "cherry", "mango"];
arr.forEach(function(item, index, _) {
console.log("[" + index + "] = '" + item + "'");
});
var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
console.log(i,j);
}
A lot cleaner...
z.forEach(j => console.log(j));
.
Commented
Mar 17, 2020 at 14:57
var myStringArray = ["hello", "World"];
myStringArray.forEach(function(val, index){
console.log(val, index);
})
Short answer: yes. You can do with this:
var myArray = ["element1", "element2", "element3", "element4"];
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
In a browser console, you can see something like "element1", "element2", etc., printed.
//Make array
var array = ["1","2","3","4","5","6","7","8","9","10"]
//Loop
for(var i = 0; i < array.length; i++){
console.log((i+1) + " --> " + array[i])
}
For the ACTUAL number for i
, you need to change (i+1)
to i
or (i)
, if you want.
Hope this helped.
Sure it's inefficient and many despise it, but it's one of the closest to the mentioned:
var myStringArray = ["Hello","World"];
myStringArray.forEach(function(f){
// Do something
})
It seems that all the variants were listed, except forEach
by lodash:
_.forEach([1, 2], (value) => {
console.log(value);
});
Just a simple one-line solution:
arr = ["table", "chair"];
// Solution
arr.map((e) => {
console.log(e);
return e;
});
.forEach()
and drop the return e;
Commented
Oct 6, 2017 at 11:09
map
implies, the function map
is for mapping a certain value to something else, hence I would not suggest using that one for this certain example.
Given an array, you can traverse it one of the many ways as follows.
1. Classic for
loop
const myArray = ['Hello', 'World'];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
2. for...of
const myArray = ['Hello', 'World'];
for (const item of myArray) {
console.log(item);
}
const myArray = ['Hello', 'World'];
myArray.forEach(item => {
console.log(item);
});
4. while
loop
const myArray = ['Hello', 'World'];
let i = 0;
while (i < myArray.length) {
console.log(myArray[i]);
i++;
}
5. do...while
loop
const myArray = ['Hello', 'World'];
let i = 0;
do {
console.log(myArray[i]);
i++;
} while (i < myArray.length);
6. Queue style
const myArray = ['Hello', 'World'];
while (myArray.length) {
console.log(myArray.shift());
}
7. Stack style
Note: The list is printed reverse in this one.
const myArray = ['Hello', 'World'];
while (myArray.length) {
console.log(myArray.pop());
}
There are multiple ways to do it in javascript. Here are the common ways of handling arrays.
Method 1:
const students = ["Arun","Jos","John","Kiran"]
for (var index = 0; index < students.length; index++) {
console.log(students[index]);
}
Method 2:
students.forEach((student, index) => console.log(student));
Method 3:
for (const student of students) {
console.log(student);
}
Well, how about this:
for (var key in myStringArray) {
console.log(myStringArray[key]);
}
It is better to use a sequential for
loop:
for (var i = 0; i < myStringArray.length; i++) {
// Do something
}
var array = ['hai', 'hello', 'how', 'are', 'you']
$(document).ready(function () {
$('#clickButton').click(function () {
for (var i = 0; i < array.length; i++) {
alert(array[i])
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<input id="clickButton" value="click Me" type="button"/>
<div id="show"></div>
Consider this:
const ITEMS = ['One','Two','Three']
let item=-1
//Then, you get looping with every call of:
ITEMS[item=item==ITEMS.length-1?0:item+1]
This answer provides an alternative to loops and array functions to iterate through an array.
In some cases it makes sense to use a recursive implementation over conventional loops and callbacks. Particularly, if you have to work with multiple arrays or nested arrays. You avoid writing nested loops to access data from multiple arrays. I also find this code easier to read and write.
/**
array is the array your wish to iterate.
response is what you want to return.
index increments each time the function calls itself.
**/
const iterateArray = (array = [], response = [], index = 0) => {
const data = array[index]
// If this condition is met. The function returns and stops calling itself.
if (!data) {
return response
}
// Do work...
response.push("String 1")
response.push("String 2")
// Do more work...
// THE FUNCTION CALLS ITSELF
iterateArray(data, response, index+=1)
}
const mainFunction = () => {
const text = ["qwerty", "poiuyt", "zxcvb"]
// Call the recursive function
const finalText = iterateArray(text)
console.log("Final Text: ", finalText()
}
Say the array being passed to iterateArray
contained objects instead of strings. And each object contained another array in it. You would have to run nested loops to access the inner array, but not if you iterate recursively.
You can also make iterateArray
a Promise.
const iterateArray = (array = [], response = []) =>
new Promise(async (resolve, reject) => {
const data = array.shift()
// If this condition is met, the function returns and stops calling itself.
if (!data) {
return resolve(response)
}
// Do work here...
const apiRequestData = data.innerArray.find((item) => {
item.id === data.sub_id
})
if (apiRequestData) {
try {
const axiosResponse = await axios.post(
"http://example.com",
apiRequestData
)
if (axiosResponse.status === 200) {
response.push(apiRequestData)
} else {
return reject("Data not found")
}
} catch (error) {
reject(error)
}
} else {
return reject("Data not found")
}
// THE FUNCTION RESOLVES AND CALLS ITSELF
resolve(iterateArray(data, response))
})
for-in
loop enumerates object properties, without an specific order, and it also enumerates inherited properties... for iterating over arrays sequential loops are always recommended...in
andof
that can both be used and do different things. Then you also haveforEach
and the ugly and annoying index based looping. Every other modern language makes looping over a collection easy and straightforward with no surprises or confusion. JS could, too, but it doesn't.