从数组末尾开始查找值的索引

时间:2018-04-22 11:28:15

标签: javascript arrays json function

我目前正在使用下面的函数在我的数组中查找值。它很棒。但是我想修改它从头开始并获得匹配的最后一个值。请帮忙

Array.prototype.indexOfObj = function (key, value) {
for (var i = 0; i < this.length;)
    if (this[i++][key] === value) return --i
return -1
}
myArr.indexOfObject("key", "value");

2 个答案:

答案 0 :(得分:1)

只需从this.length-10的最后一个索引开始for循环,然后返回当前位置:

Array.prototype.lastIndexOfObj = function (key, value) {
for (var i = this.length-1; i >= 0; i--)
    if (this[i][key] === value) return i;
return -1
}

//                        0                                 1                       2 <-- here                  3  
let myArray = [{"key":"value", "foo":"bar"}, {"key":"value", "foo":"bar"}, {"key":"value", "foo":"bar"}, {"foo":"bar"} ];

console.log(myArray.lastIndexOfObj("key", "value"));

答案 1 :(得分:0)

从最后分配i当前长度,然后减去直到0

&#13;
&#13;
Array.prototype.lastIndexOfObj = function(key, value) {
  for (var i = this.length; i--;) {
    if(this[i][key] === value) return i;
  }
    
  return -1;
}

var myArr = [{ key: 'value' }, { key: 'not value' }, { key: 'value' }, { key: 'not value' }];

console.log(myArr.lastIndexOfObj("key", "value"));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;