简体   繁体   English

underscore.js每个函数

[英]underscore.js each function

I'm using underscore.js. 我正在使用underscore.js。 I loop through the selectedCharges array using underscore each function but I cannot access the selectedCharges variable inside the loop. 我使用下划线在each函数中遍历selectedCharges数组,但无法在循环内访问selectedCharges变量。

_.each(this.selectedCharges, function(selectedCharge, key){
    if(selectedCharge._id == charge._id){
        this.selectedCharges.splice(key,1); // get error from this line  
    }
});

This happens because the scope changes inside the loop, you can keep the same scope by binding your function with this using the bind function. 发生这种情况是因为作用域在循环内发生了变化,您可以通过使用bind函数将函数与this功能绑定来保持相同的作用域。

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

Code example: 代码示例:

_.each(this.selectedCharges, function(selectedCharge, key){
    if(selectedCharge._id == charge._id){
        this.selectedCharges.splice(key,1);  
    }
}.bind(this));

Nowadays javascript has native support for most underscore features. 如今,javascript已为大多数下划线功能提供了本机支持。 See https://www.reindex.io/blog/you-might-not-need-underscore/ . 参见https://www.reindex.io/blog/you-might-not-need-underscore/

The underscore answer is: 下划线的答案是:

var filteredCharges = _.filter(this.selectedCharges, function(selectedCharge){
    return selectedCharge._id !== charge._id;
});

The native answer is: 本机答案是:

const filteredCharges = this.selectedCharges.filter(selectedCharge => {
    return selectedCharge._id !== charge._id
});

You can use the third argument which is the collection itself. 您可以使用第三个参数,即集合本身。 For example 例如

_.each(this.selectedCharges, function(selectedCharge, key, coll){

   if(selectedCharge._id == charge._id){
       coll.splice(key,1);
   }

});

Here is the documentation link: http://underscorejs.org/#each 这是文档链接: http : //underscorejs.org/#each

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

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