[英]How to access properties of an object nested within another object in Jquery?
I have been trying this for a while now and can't get it to work. 我已经尝试了一段时间,但无法正常工作。
I'm creating an object: 我正在创建一个对象:
(function( $, window) {
$.widget("mobile.multiview",$.mobile.widget, {
options: {
siteMap: []
}
});
}) (jQuery,this);
And fill it with a string and an event data object like so: 并用字符串和事件数据对象填充它,如下所示:
var _mainEventBindings = function () {
var self = this;
$(document).on("some-event", function(e, data) {
self.options.siteMap.push( { type: "external", data: data } );
});
}
This works ok. 这样就可以了。 I now have to check the stored event data.toPage property in a loop to see if the string stored there is matching the current string, so I don't add stuff twice.
现在,我必须在循环中检查存储的事件data.toPage属性,以查看存储在其中的字符串是否与当前字符串匹配,因此,我不会添加任何东西。
However I can't get it to work like this: 但是我不能让它像这样工作:
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 } );
}
}
}
So basically I want to make sure I only have "unique" records in my object. 所以基本上我想确保我的对象中只有“唯一”记录。 However the above does not work because I cannot seem to access what's stored in the object like I'm doing it.
但是上述方法不起作用,因为我似乎无法像执行此操作那样访问对象中存储的内容。 Firebug does not even bother to show an error or a console...
Firebug甚至不愿意显示错误或控制台...
Question : 问题 :
How can I access the sitemap object's 2nd parameter object's parameters...? 如何访问站点地图对象的第二个参数对象的参数...?
Thanks for help! 感谢帮助!
As it was stated in the comments, you should remove equal sign =
from the comparison in your for
loop: 如注释中所述,您应该从
for
循环的比较中删除等号=
:
for (var i = 0; i < j; i++) {
...
}
Since otherwise your loop goes out of bounds. 因为否则您的循环将越界。
Using self is not a good idea, since it adds to window. 使用自我不是一个好主意,因为它增加了窗口。 Here is an example for what you are trying to achieve.
这是您要实现的示例。
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.