我有一系列类似的对象,如下所示:
const urls = [
{
title: "title 1",
url: "https://example.com/1"
},
{
title: "title 2",
url: "https://example.com/2"
},
...
]
为了减少重复,我想到了做一个类:
class URL {
title: string
url: string
constructor(title:string, url:string) {
this.title = title
this.url = url
}
}
const link1 = new URL("title 1", "https://example.com/1")
const link2 = new URL("title 2", "https://example.com/2")
这有两个缺点:
有更好的方法吗?我的目标是在数组上运行过滤器(输入特定的
title
,输出其对应的url
)。
根据您的描述,您真正想要的只是使用标题来获取 URL 的查找。
Map
或 JS 对象,因为它们是为查找而设计的,因此可以非常快地完成它们。 e.次线性。
来自 MDN 文档:
该规范要求实现映射“平均而言,提供与集合中元素数量呈次线性关系的访问时间”。因此,它可以在内部表示为哈希表(具有 O(1) 查找)、搜索树(具有 O(log(N)) 查找)或任何其他数据结构,只要复杂度优于 O (N).
const urls = {
"title 1": "https://example.com/1",
"title 2": "https://example.com/2",
};
console.log(urls["title 1"]);
console.log(urls["Non-existing title"] ?? "No URL found for this title");
Map
const urlMap = new Map();
urlMap.set("title 1", "https://example.com/1");
urlMap.set("title 2", "https://example.com/2");
console.log(urlMap.get("title 1"));
console.log(urlMap.get("Non-existing title") ?? "No URL found for this title");
如果您的标题遵循特定模式,并且您希望明智地处理事情,而不是不必要地浪费存储空间,您也可以执行以下操作:
这是一个基于您的示例的非常简单的示例。根据标题和 URL 的复杂程度,这可能会变得更加复杂。
const urls = {
title: new URL("https://example.com"),
anothertitle: new URL("https://anothertitle.net")
};
/**
* Gets a URL with parameter for a title with a specific format.
* @param {string} title title
* @returns {URL} Url
*/
function getUrlForTitle(title) {
const [key, pathValue] = title.split(" "); // you could of course use some Regex here and throw an error if it doesn't match
const url = urls[key];
if (url === undefined) throw new Error(`No URL found for title '${title}'`);
url.pathname = `/${pathValue}`;
return url;
}
console.log(getUrlForTitle("title 1").toString());
console.log(getUrlForTitle("title 2").toString());
console.log(getUrlForTitle("title 12").toString());
console.log(getUrlForTitle("anothertitle 145").toString());
// errors
console.log(getUrlForTitle("unknowntitle 145").toString());
/* Stackoverflow: show only console */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
如果您的目标是根据标题过滤数组并检索相应的 URL,则无需创建类的实例即可实现它。您可以使用对象或 Map 将标题存储为键,将其相应的 URL 存储为值。具体方法如下:
const urls = [
{
title: "title 1",
url: "https://example.com/1"
},
{
title: "title 2",
url: "https://example.com/2"
},
];
const urlsMap = new Map(urls.map(item => [item.title, item.url]));
const getUrlByTitle = (title) => {
return urlsMap.get(title) || null;
};
const titleToSearch = "title 1";
const url = getUrlByTitle(titleToSearch);
if (url) {
console.log(`URL for ${titleToSearch}: ${url}`);
} else {
console.log(`No URL found for ${titleToSearch}`);
}
在此方法中:
urls
)。getUrlByTitle
函数将标题作为输入,并从urls
对象返回相应的URL。urls
对象中找到标题,则返回对应的URL;否则,返回 null
。这种方法消除了创建类实例的需要,并避免了内存开销。也简化了代码,更加简洁。