我试图找到一种方法来搜索对象的最新值,以及使用reverse()
或使用i-- in for loop
发现的几乎所有对象,但我想以某种方式避免它
我可以使用两个var
将其存档,如下所示:
var a = [{a:true},{a:true},{a:false}]
var b = a.filter(el=>el.a == true)
console.log(b[b.length-1])
有没有办法只使用一个这样的变量?
var a = [{a:true},{a:true},{a:false}]
a.latestValue(el=>el.a == true)
答案 0 :(得分:2)
使用find
仅获得一场比赛。
如果您不喜欢该订单,也可以reverse
订购。
var a = [{
a:true,
id: 1
},{
a:true,
id: 2,
},{
a:false,
id: 3
}]
const latestValue = a.find(el => el.a === true)
const lastValue = a.reverse().find(el => el.a === true)
console.log(latestValue);
console.log(lastValue);
答案 1 :(得分:1)
基本上,您正在寻找类似.find
的东西,除了.find
是从最后一项开始并向后迭代,而不是从第一项开始并向前迭代。尽管有内置功能,例如lastIndexOf
(类似于indexOf
,但从最后一个元素开始搜索)和reduceRight
(相同,但对于reduce
),但没有这样的功能.find
已经存在,因此最好的选择是编写自己的函数。编写起来很容易,不会像.reverse()
那样改变原始数组,也不需要创建中间数组:
function findRight(arr, callback) {
for (let i = arr.length - 1; i--; i >= 0) {
if (callback(arr[i], i, arr)) return arr[i];
}
}
var a = [{id: 1, a:true},{id: 2, a:true},{id: 3, a:false}];
console.log(
findRight(a, el => el.a === true)
);
我想可以({)使用reduceRight
,尽管我不建议这样做:
var a = [{id: 1, a:true},{id: 2, a:true},{id: 3, a:false}];
console.log(
a.reduceRight((a, el) => a || (el.a && el), null)
);
答案 2 :(得分:1)
我知道已经回答了,但认为可以用其他方式实现,所以这是我的解决方案 您可以使用JavaScript数组映射函数来获取最新值的索引,例如
注意:我已修改您的数组以包含更多元素
var a = [{a:true},{a:true},{a:false},{a:false},{a:false},{a:true},{a:true},{a:false}];
var latestIndexOfTrue = a.map(function(e) { return e.a; }).lastIndexOf(true)
console.log(latestIndexOfTrue);
/* above will give you the last index of the value you want (here i have tried with
* value true) and it will give you the index as 6 */
如果您想要整个对象,则可以使用下面的代码获取它
console.log(a[latestIndexOfTrue]);