1.假设我有一个对象数组:
const arr = [
{
label: "a",
amount: 0,
disable: true,
},
{
label: "bb",
amount: 0,
disable: true,
},
{
label: "ddd",
amount: 0,
disable: false,
},
{
label: "cc",
amount: 0,
disable: false,
},
{
label: "ddd",
amount: 0,
disable: false,
},
];
获取元素disable:false
最后一个索引的办法
方法1
function findLastIndex(array, searchKey, searchValue) {
const index = array
.slice()
.reverse()
.findIndex((x) => x[searchKey] === searchValue);
console.log(array.slice().reverse());
console.log(index);
const count = array.length - 1;
const finalIndex = index >= 0 ? count - index : index;
return finalIndex;
}
//调用
console.log(findLastIndex(arr, "disable", false));
方法2
function findLastIndex(array, predicate) {
let l = array.length;
while (l--) {
if (predicate(array[l], l, array)) return l;
}
return -1;
}
//调用
console.log(
findLastIndex(arr, (value, index, obj) => value.disable === false)
);
方法3
反转数组对我来说听起来不是很简单,所以我对我非常相似的情况的解决方案是使用map()
and lastIndexOf()
:
const lastIndex = arr.map((e) => e.disable).lastIndexOf(false);
总结
欢迎指正、补充
网友评论