How to assign the array key a value, when the key name is itself a variable
How do I identify an item in a hash array if the key of the array is only known within a variable? For example:
var key = "myKey";
var array = {myKey: 1, anotherKey: 2};
alert(array.key);
Also, how would I assign a value to that key, having identified it with the variable?
This is, of course, assuming that I must use the variable key to identify which item in the array to alert.
Thanks in adva开发者_如何学编程nce!
What you have there:-
var array = {myKey: 1, anotherKey: 2};
- is not an Array. It is a native Object
object with two properties.
An ECMAScript Array
is also an object, though a more specialized object type, having a length
property, among other things.
To answer your question, you can use the square bracket property access operators. Renaming your variable to myObj
, that would be myObj[ key ]
, where key
is an identifier that resolves to a value that is converted to a string.
For a brief explanation, see: How do I access a property of an object using a string?.
For more detail, see ECMA-262-3 in detail. Chapter 7.2. OOP: ECMAScript implementation
Use
alert(array[key]);
That is the standard syntax for what you are asking.
You can call the key like:
alert(array[key]);
With traditional array notation:
alert(array[key]);
Access it just like you would an index in an array. For the example you gave: alert(array[key]);
精彩评论