如何避免循环遍历多个数组
我正在尝试根据 url 传递一个类。目前,2 个 for 循环一直在执行。有没有办法把它写得更干净,以避免执行任何不必要的代码?
const arrCommon = ['foo1', 'foo2', 'foo3', 'foo4'];
const arrOther = ['bar1', 'bar2', 'bar3'];
const activeUrl = window.location.href;
const activePage = activeUrl.substring(activeUrl.lastIndexOf('/') + 1);
for(let i=0; i<arrCommon.length; i++) {
if (activePage == arrCommon[i])
//if 'foo1, foo2 foo3 or foo4' add class to element 1
}
for(let i=0; i<arrOther.length; i++) {
if (activePage == arrOther[i]) {
//if 'bar1' add class to element 2
//if 'bar2' add class to element 3
//...
}
}
回答
为了避免 O(n) 迭代,请使用 a SetorMap代替,它应该具有“次线性”查找时间 - 通常为 O(1)。
const setCommon = new Set(['foo1', 'foo2', 'foo3', 'foo4']);
const mapOther = new Map(['bar1', el2], ['bar2', el3], ['bar3', el4]]);
const activeUrl = window.location.href;
const activePage = activeUrl.substring(activeUrl.lastIndexOf('/') + 1);
if (setCommon.has(activePage)) {
...
}
if (mapOther.has(activePage)) {
let el = mapOther.get(activePage);
...
}