You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…