有这么一个数组
const test = [
{title: 'a'},
{title:'b'},
{title:'c'},
{title:'d'},
{title:'e'},
]
有没有快捷的方式,可以快速查找其中某项的位置,
比如 someFunction(test, {title:'d'})
-> 返回 3
有这么一个数组
const test = [
{title: 'a'},
{title:'b'},
{title:'c'},
{title:'d'},
{title:'e'},
]
有没有快捷的方式,可以快速查找其中某项的位置,
比如 someFunction(test, {title:'d'})
-> 返回 3
三种函数封装 /// 自己写了一下
function isHasElementOne(arr,value){
for(var i = 0,vlen = arr.length; i < vlen; i++){
if(arr[i] == value){
return i;
}
}
return -1;
}
简单对象应该可以这样写:
test.map(item => JSON.stringify(item)).indexOf(JSON.stringify({title: 'b'}))
// 1
function someFunction(arr, option, condition) {
//对象是否包含另一个对象
function contain(source, target, condition) {//condition 全部包含或只包含一部分
return Object.keys(target)[condition?"every":"some"](v=>target[v] == source[v]);//通过数组every和some方法
}
return arr.findIndex(v=>contain(v,option,condition));//数组的findIndex方法
}
const test = [
{title: 'a'},
{title: 'b'},
{title: 'c'},
{title: 'd'},
{title: 'e'}
]
function someFunction(test, obj) {
const { title } = obj;
for(let i = 0; i < test.length; i++){
if(test[i].title == title) return i;
}
}
someFunction(test, {title:'d'});
// 3
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
2 回答1.3k 阅读✓ 已解决
https://lodash.com/里 的_.findIndex()就是这样用的 返回下标