JavaScript对象:按名称访问变量属性为字符串

JavaScript对象:按名称访问变量属性为字符串

问题描述:

如果我有一个类似于下面的javascript对象

If I have a javascript object that looks like below

var columns = {
  left: true,
  center : false,
  right : false
}

和我有一个传递对象的函数,以及像这样的属性名称

and I have a function that is passed both the object, and a property name like so

//should return false
var side = read_prop(columns, 'right');

read_prop(object,property)的主体是什么看起来像?

你不需要它的功能 - 只需使用 括号表示法

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

这等于 点符号 var side = columns.right; ,当使用括号表示法时, 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];
}