JavaScript Foreach
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
connect.sonveer
const avengers = ['thor', 'captain america', 'hulk'];
avengers.forEach((item, index)=>{
console.log(index, item)
})
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
let colors = ['red', 'blue', 'green'];
// idx and sourceArr optional; sourceArr == colors
colors.forEach(function(color, idx, sourceArr) {
console.log(color, idx, sourceArr)
});
// Output:
// red 0 ['red', 'blue', 'green']
// blue 1 ['red', 'blue', 'green']
// green 2 ['red', 'blue', 'green']
var new_array = old_array.map(function(e) {
e.data = e.data.split(',');
return e;
});
$array = array("dog", "rabbit", "horse", "rat", "cat");
$x = 1;
$length = count($array);
foreach($array as $animal){
if($x === 1){
//first item
echo $animal; // output: dog
}else if($x === $length){
echo $animal; // output: cat
}
$x++;
}