我有对象:
var IOBreadcrumb = function () {
this.breadcrumbs = [];
this.add = function(title, url) {
var crumb = {
title: title,
url:url
};
this.breadcrumbs.push(crumb);
};
};
假设我在面包屑中添加了3个项目:
IOBreadcrumb.add('a',a);
IOBreadcrumb.add('b',b);
IOBreadcrumb.add('c',c);
我如何迭代这个并打印出标题和网址?
答案 0 :(得分:1)
您可以添加each
方法:
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]);
}
}
};
并像这样使用它:
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);
});
答案 1 :(得分:0)
添加方法
print = function(){
for (var i = 0; i < this.breadcrumbs.length; i++) {
var current = this.breadcrumbs[i];
console.log(current.title, current.url);
}
}
到你的IOBreadcrumb对象,然后只需调用它
IOBreadcrumb.print();
答案 2 :(得分:0)
each
函数。
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);
});
如果您不希望来电者直接访问$.each
,则至少应使用each
功能中的breadcrumbs
...
this.each = function(callback) {
$.each(this.breadcrumbs, callback);
}
...