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"
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