Foreach PHP like usage in JavaScript
Array
How to use foreach ( $brrs as $key => $value )
in PHP with JavaScript Array.
var arr = ['aaa', 'bbb', 'ccc'];
arr.forEach(function(element, key) {
console.log('Element', key, 'is', element);
});
--- Result: ---
Element 0 is aaa
Element 1 is bbb
Element 2 is ccc
Object
How to use foreach ( $brrs as $key => $value )
in PHP with JavaScript Object (JSON).
var brr = {'a': 'aaa', 'b':'bbb', 'c':'ccc'};
for ( const [key, value] of Object.entries(brr) ) {
console.log('Key', key, 'is', value);
}
--- Result: ---
Key a is aaa
Key b is bbb
Key c is ccc
Bonus - $crr[] = “a_data”;
How to use $crr[] = "a_data";
in PHP with JavaScript Object.
var crr = {};
crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #1"';
crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #2"';
crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #3"';
for ( const [key, value] of Object.entries(crr) ) {
console.log('Key', key, 'is', value);
}
--- Result: ---
Key 0 is Insert data like crr[] = "data #1"
Key 1 is Insert data like crr[] = "data #2"
Key 2 is Insert data like crr[] = "data #3"
To array, you can use push function.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
독자 의견
저자 @richard 에게 의견 남기기: