简体   繁体   English

如何遍历此Javascript对象?

[英]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: 可以说我在面包屑中添加了3个项目:

IOBreadcrumb.add('a',a);
IOBreadcrumb.add('b',b);
IOBreadcrumb.add('c',c);

How can I iterate over this and print out the title, and the url? 我该如何遍历并打印出标题和网址?

You could add an each method: 您可以添加一个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]);
       }
    }

  };

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对象,然后调用它

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. 唯一的改进是,如果您使用的是jquery,则无需实现自己的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);
});

At the very least you should use $.each from your each function if you don't want callers to access breadcrumbs directly 如果您不希望调用者直接访问breadcrumbs则至少应在each函数中使用$.each

...
this.each = function(callback) {
   $.each(this.breadcrumbs, callback);
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM