var array = ['a', 'b', 'c'];
array[0].property = 'value';
alert(array[0].property);
alert(array[0].property = 'value');
alert(array[0].property);
The result? undefined
, 'value'
, then undefined
Why isn't this code working as expected?
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.
JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.
arrays are normal objects and their elements are properties with names 0, 1, .. etc. arrays also have a special properties lenght and many function that can manipulate the elements.
Arrays are objects and therefore you can add your own properties to them: var arr = [1, 2, 3]; arr.
The Array is irrelevant - you're trying to set a property on a primitive:
A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.
If you absolutely must use a property to carry this additional information around in a string, an alternative would be to use the object equivalent:
>>> var array = [new String('a'), new String('b'), new String('c')];
>>> array[0].property
undefined
>>> array[0].property = 'value'
"value"
>>> array[0].property
"value"
A potential gotcha to look out for if you do this and later need to detect that the value is a string:
>>> var a = ['s', new String('s')];
>>> a.map(function(s) { return typeof s; });
["string", "object"]
>>> a.map(function(s) { return s instanceof String });
[false, true]
>>> a.map(function(s) { return Object.prototype.toString.call(s) == '[object String]' });
[true, true]
Your array elements are string literals. JavaScript makes it seem like string literals are objects and have properties, but what's actually happening when you do array[0].property
is that JavaScript is creating a temporary object for your string and assigning the property to that.
That's why the middle alert works correctly and the others don't. If you declared your array like:
var array = [new String('a'), new String('b'), new String('c')];
all three would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With