var arr = new Array(); // Empty
arr[ "Pi" ] = 3.14;
arr[ "Today" ] = new Date();
arr[ "Greeting" ] = "Hello";
alert( arr["Greeting"] ); // 'Hello' - array brackets
alert( arr["greeting"] ); // undefined, case mismatch
alert( arr.Greeting ); // 'Hello' - object dot notation
Caveat: in bracket notation, the key must be a quoted string; the key is case-sensitive.
var greetings = {"AM":"Good morning","PM":"Good afternoon","6PM":"Good evening"};
alert( greetings.AM );
alert( greetings["AM"] );
alert( greetings["6PM"] ); // Works fine
// alert( greetings.6PM ); // Error - property cannot start with a number
Note: if an associative index starts with a number, you cannot use dot notation. A JavaScript property cannot start with a number → use bracket notation to access that element's value.
var str = "I learn JavaScript";
alert( str.length ); // 18 [characters]
alert( str["length"] ); // Same
arr["1"] = "Apple"; // Same as saying arr[1]
arr[1] = "Tomato"; // Just overwrote the first one
alert( arr[1] +"\n"+ arr["1"] );
$arr = array(
'Pi'=>3.14,
'Today'=>date('F j, Y'),
'Greeting'=>'Hello'
);
print_r( $arr ); // Display the array and its keys