How to make simple php's foreach equivalent in Javascript?
The closest construct is
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
console.log(n+'='+a[n]);
}
In JQuery, The $.each
function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(index, value) {
// work with value
});
For plain Javascript?
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
For you exists two way.
First when data is in object (in example it is in my_list) and second when data is exactly in array (in example it is my_array)
In any case you can use JavaScript For...In statement
Example:
<script type="text/javascript" charset="utf-8">
var data;
var my_list = {2:'Mike', 4:'Peter', 7:'Sam', 10:'Michael'};
var my_array = new Array();
my_array[2] = 'Mike';
my_array[4] = 'Peter';
my_array[7] = 'Sam';
my_array[10] = 'Michael';
data = '';
for(index in my_list) {
data += (index+'='+my_list[index]+"\n");
}
console.log(data);
data = '';
for(index in my_array) {
data += (index+'='+my_array[index]+"\n");
}
console.log(data);
</script>
In both cases console output will be:
2=Mike
4=Peter
7=Sam
10=Michael
Actually please read http://www.w3schools.com/js/js_loop_for_in.asp