答案:通过JavaScript类封装数据存储与查询逻辑,利用localStorage持久化数据,使用递归方式解析支持$and、$or、$not及多种比较操作符的查询条件,实现本地动态查询数据库。

用JavaScript实现一个支持动态查询的本地数据库,说白了,就是利用JS在客户端环境(比如浏览器或Node.js)管理数据。这通常不依赖于传统的数据库服务,而是通过在内存中维护数据结构(如数组或对象集合),并编写一套自定义的查询解析和过滤逻辑来完成。它更像是一个轻量级的数据管理层,能让你的应用在没有后端支持或需要离线工作时,也能灵活地操作数据。
要构建一个支持动态查询的本地数据库,核心在于两个方面:数据存储机制和一套灵活的查询引擎。在我看来,最直接的做法是创建一个JavaScript类来封装这些功能。
首先,我们需要一个地方来存放数据。在浏览器环境,
localStorage
IndexedDB
localStorage
数据结构上,我们通常会用一个JavaScript数组来存储记录,每条记录是一个JavaScript对象。为了支持查询和更新,每条记录最好有个唯一的ID。
立即学习“Java免费学习笔记(深入)”;
// 辅助函数:用于评估单个条件
function evaluateCondition(recordValue, operator, queryValue) {
switch (operator) {
case '$eq': return recordValue === queryValue; // 等于
case '$ne': return recordValue !== queryValue; // 不等于
case '$gt': return recordValue > queryValue; // 大于
case '$gte': return recordValue >= queryValue; // 大于等于
case '$lt': return recordValue < queryValue; // 小于
case '$lte': return recordValue <= queryValue; // 小于等于
case '$contains': return typeof recordValue === 'string' && recordValue.includes(queryValue); // 字符串包含
case '$startsWith': return typeof recordValue === 'string' && recordValue.startsWith(queryValue); // 字符串开头
case '$endsWith': return typeof recordValue === 'string' && recordValue.endsWith(queryValue); // 字符串结尾
case '$in': return Array.isArray(queryValue) && queryValue.includes(recordValue); // 值在数组中
case '$nin': return Array.isArray(queryValue) && !queryValue.includes(recordValue); // 值不在数组中
default: return false; // 未知操作符,默认不匹配
}
}
class LocalDatabase {
constructor(dbName = 'my_local_db') {
this.dbName = dbName;
this.data = this._loadData();
// 确保ID递增,避免重复
this.nextId = this.data.length > 0 ? Math.max(...this.data.map(item => item.id || 0)) + 1 : 1;
}
_loadData() {
try {
const storedData = localStorage.getItem(this.dbName);
return storedData ? JSON.parse(storedData) : [];
} catch (e) {
console.error(`Error loading data for ${this.dbName}:`, e);
return [];
}
}
_saveData() {
try {
localStorage.setItem(this.dbName, JSON.stringify(this.data));
} catch (e) {
console.error(`Error saving data for ${this.dbName}:`, e);
}
}
// 插入数据
insert(record) {
if (!record || typeof record !== 'object') {
throw new Error("Invalid record: Must be an object.");
}
const newRecord = { ...record, id: this.nextId++ };
this.data.push(newRecord);
this._saveData();
return newRecord;
}
// 查询数据 - 核心功能
find(query = {}) {
if (Object.keys(query).length === 0) {
return [...this.data]; // 如果没有查询条件,返回所有数据
}
return this.data.filter(record => this._matchRecord(record, query));
}
// 内部方法:判断单条记录是否匹配查询条件
_matchRecord(record, query) {
// 处理顶层的逻辑操作符 ($and, $or, $not)
if (query.$and) {
return query.$and.every(subQuery => this._matchRecord(record, subQuery));
}
if (query.$or) {
return query.$or.some(subQuery => this._matchRecord(record, subQuery));
}
if (query.$not) {
return !this._matchRecord(record, query.$not);
}
// 处理字段级别的查询条件
for (const key in query) {
// 跳过已经处理过的逻辑操作符
if (key.startsWith('$')) continue;
const queryValue = query[key];
const recordValue = record[key];
if (typeof queryValue === 'object' && queryValue !== null && !Array.isArray(queryValue)) {
// 如果查询值是一个对象,说明它包含操作符,例如 { age: { $gt: 30 } }
for (const op in queryValue) {
if (!evaluateCondition(recordValue, op, queryValue[op])) {
return false; // 任何一个操作符不匹配,则整条记录不匹配
}
}
} else {
// 简单相等匹配,例如 { name: "Alice" }
if (recordValue !== queryValue) {
return false;
}
}
}
return true; // 所有条件都匹配
}
// 更新数据
update(query, updates) {
let updatedCount = 0;
this.data = this.data.map(record => {
if (this._matchRecord(record, query)) {
updatedCount++;
return { ...record, ...updates }; // 合并更新
}
return record;
});
if (updatedCount > 0) {
this._saveData();
}
return updatedCount;
}
// 删除数据
delete(query) {
const initialLength = this.data.length;
this.data = this.data.filter(record => !this._matchRecord(record, query));
if (this.data.length < initialLength) {
this._saveData();
}
return initialLength - this.data.length; // 返回删除的数量
}
}
// 示例用法:
// const userDB = new LocalDatabase('users');
// userDB.insert({ name: 'Alice', age: 30, city: 'New York' });
// userDB.insert({ name: 'Bob', age: 25, city: 'London' });
// userDB.insert({ name: 'Charlie', age: 35, city: 'New York' });
//
// console.log('所有用户:', userDB.find());
// console.log('年龄小于30的用户:', userDB.find({ age: { $lt: 30 } }));
// console.log('纽约或伦敦的用户:', userDB.find({ $or: [{ city: 'New York' }, { city: 'London' }] }));
//
// userDB.update({ name: 'Alice' }, { age: 31 });
// console.log('更新Alice后:', userDB.find({ name: 'Alice' }));
//
// userDB.delete({ age: { $lt: 26 } });
// console.log('删除年龄小于26的用户后:', userDB.find());这段代码展示了一个基本的
LocalDatabase
find
_matchRecord
{ name: 'Alice' }{ age: { $gt: 30 } }$and
$or
$not
设计一个高效的查询解析器,其实就是如何让
_matchRecord
我们上面用的查询对象模型(比如
{ age: { $gt: 30 } }{ $or: [...] }核心思想:
$gt
$contains
evaluateCondition
$and
$or
$not
_matchRecord
$and
$or
$not
效率考量: 对于本地、内存型的数据库,当数据量不大时(几百到几千条记录),这种简单的线性过滤(
Array.prototype.filter
这时,可以考虑一些优化手段,但它们会增加实现的复杂性:
id
以上就是如何用JavaScript实现一个支持动态查询的本地数据库?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号