3.19 findLastIndex

3.19.1语法

_.findLastIndex(array, predicate, [context])

3.19.2说明

和_.findIndex类似,但反向迭代数组,当predicate通过真检查时,最接近末端的索引值将被返回。

3.19.3示例

示例一:如果有重复的,则返回最后一个index


var users = [{'id': 1, 'name': 'Bob', 'last': 'Brown'},
             {'id': 2, 'name': 'Ted', 'last': 'White'},
             {'id': 3, 'name': 'Frank', 'last': 'James'},
             {'id': 4, 'name': 'Ted', 'last': 'Jones'}];
var res = _.findLastIndex(users, {
  name: 'Ted'
});
console.log(res);//=>3

var array = [1,2,3,4,5,1,2,3];
var res = _.findLastIndex(array, function(value){
    return value===2;
});
console.log(res);//=>6


var res = _.findLastIndex([4, 6, 7, 12], function(value,index,list){
    console.log(index,value,list);
    //3 12 [4, 6, 7, 12]
    return value === 12;
});
console.log(res);//=>3

示例二:context参数,改变function指向的this.


var res = _.findLastIndex([4, 6, 7, 12], function(value,index,list){
    console.log(this);
    //[4, 6, 7]
    //[4, 6, 7]
    //[4, 6, 7]
    return value === 6;
},[4,6,7]);
console.log(res);//=>1