Asked 8 years ago
18 Nov 2016
Views 1070
sarah

sarah posted

foreach in javascript

Hi

i used foreach in php for looping like

foreach($product as $value){
echo $value->name;
}


but i want to use same with JavaScript . because i getting product list in json by ajax and i want to load it with JavaScript in html .
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

yes JavaScript Support forEach , see the following code


var jsondata=['product 1','product 2','Product 3 '];
jsondata.forEach(function (value,key) {
 alert(value);
      });


you can use forEach as you do in php but difference is you need to pass reference variable and second argument is key which array key to function argument forEach

so
foreach($array as $key=>$value) { //code here } become array.forEach(funcion(value,key){ //code here });
Post Answer