【问题标题】:What is the difference between underscore _.each and forEach?下划线 _.each 和 forEach 有什么区别?
【发布时间】:2016-07-20 22:44:31
【问题描述】:

我研究 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'));
    });

【问题讨论】:

  • Backbone 有 _.each 方法的代理,你必须在你的情况下使用它:todos.each(function(todo) {...})

标签: javascript foreach underscore.js each


【解决方案1】:

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

 _.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

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 2013-03-28
    • 2021-09-02
    • 2016-11-08
    • 1970-01-01
    • 2011-09-30
    • 2019-09-21
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多