如果我有一个javascript对象,如下所示

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

我有一个传递对象和属性名的函数

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

read_prop(对象,属性)的主体是什么样子的?


当前回答

因为我通过上面的答案帮助了我的项目(我问了一个重复的问题,并在这里被引用),我提交了一个答案(我的测试代码)在var内嵌套时的括号符号:

<html> <head> <script type="text/javascript"> function displayFile(whatOption, whatColor) { var Test01 = { rectangle: { red: "RectangleRedFile", blue: "RectangleBlueFile" }, square: { red: "SquareRedFile", blue: "SquareBlueFile" } }; var filename = Test01[whatOption][whatColor]; alert(filename); } </script> </head> <body> <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p> <br/> <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p> <br/> <p onclick="displayFile('square', 'red')">[ Sq Red ]</p> </body> </html>

其他回答

你不需要一个函数-简单地使用括号符号:

var side = columns['right'];

这等于点表示法,var side = columns.right;,除了在使用括号表示法时,right也可以来自变量、函数返回值等。

如果你需要一个函数,它是:

function read_prop(obj, prop) {
    return obj[prop];
}

要回答下面与原始问题没有直接关系的一些注释,可以通过多个括号引用嵌套对象。如果你有一个像这样的嵌套对象:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

可以通过如下方式访问c的属性x:

var cx = foo['c']['x']

如果一个属性是undefined,试图引用它将返回undefined(不是null或false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

因为我通过上面的答案帮助了我的项目(我问了一个重复的问题,并在这里被引用),我提交了一个答案(我的测试代码)在var内嵌套时的括号符号:

<html> <head> <script type="text/javascript"> function displayFile(whatOption, whatColor) { var Test01 = { rectangle: { red: "RectangleRedFile", blue: "RectangleBlueFile" }, square: { red: "SquareRedFile", blue: "SquareBlueFile" } }; var filename = Test01[whatOption][whatColor]; alert(filename); } </script> </head> <body> <p onclick="displayFile('rectangle', 'red')">[ Rec Red ]</p> <br/> <p onclick="displayFile('square', 'blue')">[ Sq Blue ]</p> <br/> <p onclick="displayFile('square', 'red')">[ Sq Red ]</p> </body> </html>

ThiefMaster的答案是100%正确的,尽管我遇到了一个类似的问题,我需要从嵌套的对象(对象中的对象)中获取一个属性,所以作为他的答案的替代方案,你可以创建一个递归的解决方案,允许你定义一个命名法来抓取任何属性,而不管深度:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

你的字符串引用一个给定的属性类似property1.property2

JsFiddle中的代码和注释。