let arr = [1,2,3]
// forEach accepts a function, and each value in array is passed to the
// function. You define the function as you would any regular
// function, you're just doing it inside the forEach loop
arr.forEach(function(value){
console.log(value)
})
// you also have access to the index and original array:
arr.forEach(function(value, idx, array){
console.log(idx, value, array)
})
// it's common for the arrow notation to be used: it's effectively
// the same thing but the function keyword is removed and the syntax is
// a bit different
arr.forEach((value) => {
console.log(value)
})
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(getArrayValues);
function getArrayValues(item, index) {
console.log( index + ":" + item);
}
/*
result:
0:apple
1:orange
2:cherry
*/
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++;
}