下划线_.each和forEach有什么区别?

时间:2016-04-01 07:59:39

标签: javascript foreach underscore.js each

我研究Backbone n下划线 有人帮帮我 我不知道该模型未定义_.each()。

 var todos = new Backbone.Collection();

    todos.add([
        { title: 'go to Belgium.', completed: false },
        { title: 'go to China.', completed: false },
        { title: 'go to Austria.', completed: true }
    ]);

    // iterate over models in the collection 
    todos.forEach(function(model){
        console.log(model.get('title'));
    });
    // Above logs:
    // go to Belgium.
    // go to China.
    // go to Austria.

为什么模型未定义???

    /*underscoreJS  model is undefined...*/
    _.each(todos, function (model) {
        console.log(model.get('title'));
    });

1 个答案:

答案 0 :(得分:0)

对于下划线,您需要这样做:

 _.each(todos.models, function(model) {
   console.log(model.get('title'));
 });

你做的原因

 var todos = new Backbone.Collection();

 todos.add([{
   title: 'go to Belgium.',
   completed: false
 }, {
   title: 'go to China.',
   completed: false
 }, {
   title: 'go to Austria.',
   completed: true
 }]);

Backbone返回一个代理对象,该对象将模型数组保存在todos.models

工作代码here