How can I iterate over this Javascript object?
I have the object:
var IOBreadcrumb = function () {
this.breadcrumbs = [];
this.add = function(title, url) {
var crumb = {
title: title,
url:url
};
this.breadcrumbs.push(crumb);
};
};
Lets say I add 3 items to breadcrumbs:
IOBreadcrumb.add('a',a);
IOBreadcrumb.add('b',b);
IOBreadcrumb.add('c',c);
How can I iterate over th开发者_如何学Pythonis and print out the title, and the url?
You could add an each
method:
var IOBreadcrumb = function IOBreadcrumb() {
this.breadcrumbs = [];
this.add = function(title, url) {
var crumb = {
title: title,
url:url
};
this.breadcrumbs.push(crumb);
};
this.each = function(callback) {
for (var i = 0; i < this.breadcrumbs.length; i++) {
callback(this.breadcrumbs[i]);
}
}
};
And use it like this:
var ioBc = new IOBreadcrumb();
ioBc.add('a',a);
ioBc.add('b',b);
ioBc.add('c',c);
ioBc.each(function(item) {
console.log(item.title + ' ' + item.url);
});
add a method
print = function(){
for (var i = 0; i < this.breadcrumbs.length; i++) {
var current = this.breadcrumbs[i];
console.log(current.title, current.url);
}
}
to your IOBreadcrumb object, and then just invoke it
IOBreadcrumb.print();
Jason's answer is almost there. The only improvement is that there is no need to implement your own each
function if you're using jquery.
var ioBc = new IOBreadcrumb();
ioBc.add('a',a);
ioBc.add('b',b);
ioBc.add('c',c);
$.each(ioBc.breadcrumbs, function(item) {
console.log(item.title + ' ' + item.url);
});
At the very least you should use $.each
from your each
function if you don't want callers to access breadcrumbs
directly
...
this.each = function(callback) {
$.each(this.breadcrumbs, callback);
}
...
精彩评论