# Table.find()
Table.find()
如果你想在数据库中查找数据,还可以使用 Table.find() 方法:
const data = [
{
name: 'luke',
age: 22
},
{
name: 'elaine',
age: 23
}
];
user.addMany(data)
.then(() => {
user.find((item) => {
return item.age > 22;
})
.then((data) => console.log(data))
// { name: 'elaine', age: 23 }
});
Table.find(fn) 接受一个函数 fn 作为参数,这个函数的返回值应当为 true 和 false
用法其实和 JS 数组方法 Array.find() 如出一辙
这个方法在内部会从头遍历整个表(使用 IndexedDB 的 Cursor),然后把每一次的结果放进 fn 执行,如果 fn 的返回值为 true(内部使用 if(fn()) 判断),就返回当前的结果,停止遍历
这个方法只会返回第一个满足条件的值,如果需要返回所有满足条件的值,请使用 Table.findAll(),用法与 Table.find() 一致,但是会返回一个数组,包含所有满足条件的值
Table.find() 与 Table.get() 的区别
-
find() 使用判断函数 + 遍历表的方法
- 使用上更灵活,因为判断函数由用户决定
-
get() 使用数据库索引进行搜索
- 性能更高,尤其是在大量数据中进行搜索的时候