3 回答

TA貢獻1777條經驗 獲得超10個贊
您不需要它的功能 - 只需使用括號表示法:
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}};
您可以訪問財產x
的c
,如下所示:
var cx = foo['c']['x']
如果屬性未定義,試圖引用它會返回undefined
(不null
或false
):
foo['c']['q'] === null// returns falsefoo['c']['q'] === false// returns falsefoo['c']['q'] === undefined// returns true

TA貢獻1784條經驗 獲得超9個贊
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中的代碼和注釋。

TA貢獻1853條經驗 獲得超9個贊
由于我通過上面的答案得到了我的項目幫助(我問了一個重復的問題并在這里提到了),我在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>
添加回答
舉報