I’ve this array in JS:
datas = [
["Elem1", "Data1"],
["Elem2", "Data2"],
["Elem3", "Data3"]
];
I’m using:
datas.forEach((element, index) => {
alert(element.Elem1);
});
But it don’t work.
How I can loop to get each result ?
Thanks.
3
Answers
Yes, It’s simple.
Option 1: Simple For Loops
Option 2: For of
Option 3:
Array.prototype.forEach
There are more exciting ways to try, read the MDN Documentation to get more info.
The provided array is a two-dimensional array, where each element is an array itself containing two values. To access the values within each subarray, you need to use indices rather than object properties.
To loop through the array and retrieve each value, you can modify your code as follows:
This will display "Elem1", "Elem2", and "Elem3" in separate alert dialogs. If you want to access the second value in each subarray, you can use
element[1]
instead.Remember that indices in JavaScript start from 0, so
element[0]
retrieves the first value in each subarray.If you want to loop all the children dynamically, you do like the following:
You can flatten the array and use a simple loop: