I’ve just started studying PHP and I came across something called associative arrays. It allows you to do the following:
$soccerTeam = array();
$soccerTeam['andy'] = 10;
The equivalent in JS would be:
var soccerTeam = new Array();
soccerTeam['andy'] = 10;
I tried this out in JS in FireBug and it seemed to work. My only question is, is it a good idea? I could not find any JS documentation on it and I even found an article that said it was a bad practice. And if it is bad in JS, is it bad in PHP as well?
n JavaScript associative arrays are called Objects and almost the entire language uses them for almost everything.
var soccerTeam = {}; // this is an object
soccerTeam['andy'] = 10
alert(soccerTeam['andy']);
alert(soccerTeam.constructor);
var soccerTeam = []; // this is an array
soccerTeam['andy'] = 10
alert(soccerTeam['andy']);
alert(soccerTeam.constructor);
all arrays are objects, all objects are not arrays
That’s the difference between associative arrays and ordinary arrays. In JavaScript any associative array you define is actually just defined as an object ans ANY object can be referenced as if it were an associative array.
JavaScript does not have a separate data type for associative arrays and any associative arrays you attempt to create will just create an object.
Note that an Arrayi is something completely different from an associative array and that none of the Array methods can be used on an associative array in JavaScript because those methods only work for Arrays and in JavaScript an associative array is an Object and not an Array.