I’m new to javascript, coming from PHP. I have worked with it a bit in the past but want to dive in deeper. I have a few questions.
1
Are associative arrays just constructed like objects or is there a special syntax for them, like in PHP with ‘key’ => ‘value’? I realize arrays are objects in JS (since almost everything is), but I am wondering if there is a special associative array type or if I should really be thinking “objects” not “associative arrays” in JS.
2
How do I iterate over the arrays but save the contents?
var test_array = [1, 2, 3, 4]
test_array.forEach(function(key, value)
{
if (key == 1) {
var result = key;
}
});
console.log(key) // should be 1, instead, I get a reference error, it is undefined.`
3
Can you use .forEach over a normal object? I could not get it to work with objects but only with non-associative arrays.
4
With a for loop, is there any way to get the value of an element in an array or object being iterated over, rather than just the key of the element?
var object_as_array = {day: 'monday', 'month' : 'march', 'season' : { 'summer' : 'hot' } };
for (index = 0; index < object_as_array.length; ++index) {
console.log(object_as_array[index]);
}
5
How do I copy an entire object as text in (any) browser’s dev tools? (I’ll use whatever it takes.) Right now I can copy the top level, which is usually something like { Object, Object, Object } so not very helpful. I just want to be able to copy and paste the entire contents of the object after I send it to console through console.log(object). Right clicking and copying it only copied the first level. (Preferably only for direct properties of the object, but I will take whatever I can get, including functions and inherited properties if that is the only way.)
6
. In php, we can do:
$colors = ['red', 'blue', 'green'];
$found_red = false;
foreach ($colors as $color) {
if ($color === 'red') {
$found_red = true;
}
var_dump($found_red); // true
But I don’t know how to do this basic construction in JS, for either arrays or associative arrays or plain objects (if there is a difference). I think this is some sort of scoping issue.
Any help with any of these would be appreciated.