[英]How to access array element inside JS object?
我在訪問數組內的元素時遇到問題。 這是一個示例代碼:
var Core = {
customNames: {
'1': [ 'Power Off' ],
'21': [ 'TV', 'Bedroom' ]
},
render: function() {
$.each( Core.devices.result, function( i, obj ) {
var name = Core.customNames[obj.idx][1] ? Core.customNames[obj.idx][1] : obj.Name;
});
}
};
obj.idx 是一個變量,假設值為 21。在這種情況下如何訪問“卧室”?
在渲染函數中試試this
!
render: function() {
var that = this;
$.each( this.devices.result, function( i, obj ) {
var name = that.customNames[obj.idx][1] ? that.customNames[obj.idx][1] : obj.Name;
});
}
您必須設置that
因為$.each
的范圍$.each
發生變化!
這是我測試過的一個例子,它有效:
var thing = { customNames: { '1': [ 'Power Off' ], '21': [ 'TV', 'Bedroom' ] }, log: function(){ console.log("This got logged inside here: " + this.customNames['21'][0]); } } thing.log()
你好!
解決了! 訪問數組元素沒有問題,但 customNames 對象不完整。 正確的代碼:
var name = Core.customNames[obj.idx] != undefined ? Core.customNames[obj.idx][0] : obj.Name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.