JavaScript 查找表

Shraddha Paghdar 2023年10月12日
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。该数组包含产品信息,例如产品 ColorSizePrice

根据最终用户选择的过滤器,我们需要显示 Price 信息。为了加快搜索速度,我们将创建一个查找表,其中 ColorSize 信息作为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"

演示

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

相关文章 - JavaScript Table