簡體   English   中英

如何訪問嵌套在Jquery中另一個對象內的對象的屬性?

[英]How to access properties of an object nested within another object in Jquery?

我已經嘗試了一段時間,但無法正常工作。

我正在創建一個對象:

(function( $, window) { 

    $.widget("mobile.multiview",$.mobile.widget, {

        options: {  
            siteMap: []
            }
        });
 }) (jQuery,this);

並用字符串和事件數據對象填充它,如下所示:

var _mainEventBindings = function () {
    var self = this;

    $(document).on("some-event", function(e, data) {
       self.options.siteMap.push( { type: "external", data: data } );
       });
 }

這樣就可以了。 現在,我必須在循環中檢查存儲的事件data.toPage屬性,以查看存儲在其中的字符串是否與當前字符串匹配,因此,我不會添加任何東西。

但是我不能讓它像這樣工作:

var j = self.options.siteMap.length;
if (j == 0 ){
    alert("added entry");
    self.options.siteMap.push( { type: "external", data: data } );
    } else {
        for ( i = 0; i <= j; i++) {
            console.log("run "+i);
            console.log( self.options.siteMap);
            console.log( self.options.siteMap[i]);
            if ( data.toPage != self.options.siteMap[i]['data.toPage'] ){
                self.options.siteMap.push( { type: "external", data: data } );
                }
            }
        }

所以基本上我想確保我的對象中只有“唯一”記錄。 但是上述方法不起作用,因為我似乎無法像執行此操作那樣訪問對象中存儲的內容。 Firebug甚至不願意顯示錯誤或控制台...

問題
如何訪問站點地圖對象的第二個參數對象的參數...?

感謝幫助!

如注釋中所述,您應該從for循環的比較中刪除等號=

for (var i = 0; i < j; i++) {
   ...
}

因為否則您的循環將越界。

使用自我不是一個好主意,因為它增加了窗口。 這是您要實現的示例。

var s = {},  //create an empty object
    i, siteMap;
s.options = {};
s.options.siteMap = []; //our array

//let's add some data to siteMap array
s.options.siteMap = [{'type': "external0", 'data': 'data0'}, {'type': "external1", 'data': 'data1'}, {'type': "external2", 'data': 'data2'}];

//get the siteMap's properties' property
siteMap = s.options.siteMap;
for (i in siteMap) {
  console.log(siteMap[i].type);  //will print external0, external1 etc.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM