JavaScript 查找表
在今天的帖子中,我们将学习使用 JavaScript 中的一种简单方式创建查找表。
JavaScript 中的查找表
查找表是在数据处理中用更简单的数组索引操作替换运行时计算的数组。该过程称为直接寻址。JavaScript 使用对象作为查找函数。
这是用于提高搜索结果查询性能的著名算法。让我们通过下面的例子来理解它。
假设你经营一个电子商务网站,其主要功能是列出产品。根据用户选择的过滤器,显示产品的价格。
每次访问服务器时查询此输出都会降低性能。你可以根据最常用的过滤器对产品进行索引以解决此问题。
const DBProductArray = [
{Color: 'Red', Size: 'Small', Price: '$450'},
{Color: 'Red', Size: 'Medium', Price: '$460'},
{Color: 'Red', Size: 'Large', Price: '$460'},
{Color: 'Red', Size: 'Extra-Large', Price: '$470'},
{Color: 'White', Size: 'Small', Price: '$650'},
{Color: 'White', Size: 'Medium', Price: '$660'},
{Color: 'White', Size: 'Large', Price: '$670'},
{Color: 'White', Size: 'Extra-Large', Price: '$680'}
];
const lookupMap = {};
由于服务器的 List API 操作,我们在上面的示例中有一个 DBProductArray
。该数组包含产品信息,例如产品 Color
、Size
和 Price
。
根据最终用户选择的过滤器,我们需要显示 Price
信息。为了加快搜索速度,我们将创建一个查找表,其中 Color
和 Size
信息作为键
,Price
信息作为值
。
const arrayLength = DBProductArray.length;
for (i = 0; i < arrayLength; i++) {
var record = DBProductArray[i];
if (typeof lookupMap[record.Color] === 'undefined')
lookupMap[record.Color] = {};
lookupMap[record.Color][record.Size] = record.Price;
}
console.log(lookupMap);
输出:
{
Red: {
Extra-Large: "$470",
Large: "$460",
Medium: "$460",
Small: "$450"
},
White: {
Extra-Large: "$680",
Large: "$670",
Medium: "$660",
Small: "$650"
}
}
上面的代码循环遍历 DBProductArray
并检查颜色信息是否存在。我们创建颜色作为嵌套对象的键(如果存在)。
嵌套对象包含作为键的 size
和作为值的 price
。你现在无需查询数据库即可查看选定产品的定价信息,从而节省响应时间并提高性能。
const selectedColor = 'White';
const selectedSize = 'Large';
console.log(lookupMap[selectedColor][selectedSize]);
尝试在任何支持 JavaScript 的浏览器中运行上述代码片段;它将显示以下结果。
输出:
"$670"
演示
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。