如何將以下內容寫入 foreach,因為我并不總是需要 urlModule 中的所有資源型別。我稍后呼叫 urlModule,因此需要保留該變數。
// 來自 API 的回應
const resources = [{
resourceType: 'brand',
url: 'brandUrl'
}, {
resourceType: 'product',
url: 'productUrl'
}, {
resourceType: 'category',
url: 'categoryUrl'
}, {
resourceType: 'document',
url: 'documentUrl'
}];
將 .map 更改為 forEach 以避免“預期在箭頭函式末尾回傳值”警告?
const urlModule = resources.map((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
}
}
if (resourceType === 'product') {
return {
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
}
}
if (resourceType === 'document') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
}
}
})
return [
{
url: '/',
changefreq: 'daily',
priority: 1,
},
{
url: '/account',
changefreq: 'daily',
priority: 1,
},
...urlModule,
]
},
uj5u.com熱心網友回復:
然后,您必須在回圈之外創建新變數。
let urlModule = [];
resources.forEach((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
urlModule.push({
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
})
}
if (resourceType === 'product') {
urlModule.push({
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
})
}
if (resourceType === 'document') {
urlModule.push({
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
})
}
});
console.log(urlModule);
uj5u.com熱心網友回復:
有幾種方法可以解決這個問題,并且forEach可能是最不優雅的。
關于“期望在箭頭函式的末尾回傳一個值”,這實際上很有用,我個人希望避免在某些情況下沒有回傳的函式,因為它的意圖不太清楚。這個警告告訴你你有不透明的邏輯,但是forEach為了避免這種情況而進行重構也有它自己的問題。
映射器是可重用的,所以提取它
首先,我們可以提取地圖回呼,因為無論我們如何組織其余代碼,我們都可以重用邏輯。
重構forEach
要使用 forEach,我們需要在映射器回呼范圍之外建立一個變數,我們將在其中插入預期的輸出。就我個人而言,我盡量避免這種情況,因為宣告經常與forEach呼叫分離,并且可能導致對參考變數來自何處的混淆(可能是全域的,而不是使用外部范圍)。
重構到map那時filter
在這個變體中,我們保留了現有的地圖。這會導致某些陣列條目為undefined,但可以輕松過濾掉這些條目。在我的示例中,我使用雙邏輯不將值轉換為布林值,正如filter. 任何值都undefined將回傳false并被洗掉。
重構為reduce
Reduce 與forEach變體類似,但優點是將接收變數封裝到reduce呼叫中,因此我們的回呼沒有外部依賴。在這里,我在回呼中重用了現有mapper的reduce,但如果這是您唯一使用它的地方,您可以將邏輯合并到回呼中。
獎金 -switch而不是if
我個人會重構mapper使用switch. 如所寫,即使在匹配之后也會評估多個條件,這可能會在將來進行修改時導致錯誤。計算開銷可能可以忽略不計。我發現這switch向讀者表明“其中只有一個適用”
const resources = [{
resourceType: 'brand',
url: 'brandUrl'
}, {
resourceType: 'product',
url: 'productUrl'
}, {
resourceType: 'category',
url: 'categoryUrl'
}, {
resourceType: 'document',
url: 'documentUrl'
}];
// ------------------------------ Our mapping callback
const mapper = (resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
}
}
if (resourceType === 'product') {
return {
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
}
}
if (resourceType === 'document') {
return {
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
}
}
return undefined;
}
// ------------------------------ forEach instead of map
const foreach = []
resources.forEach(resource => {
const item = mapper(resource)
if (item !== undefined) {
foreach.push(item)
}
})
console.log('foreach', foreach)
// ------------------------------ Map then filter
const mapFilter = resources
.map(mapper)
.filter(item => !!item)
console.log('mapfilter', mapFilter);
// ------------------------------ Reduce
const reduce = resources
.reduce((acc, cur) => {
const item = mapper(cur)
if (item !== undefined) {
acc.push(item)
}
return acc
}, [])
console.log('reduce', reduce)
uj5u.com熱心網友回復:
從我上面的評論...
“為了避免 linter 警告而從正確的方法更改為不太合適的方法并不能防止代碼異味。一個只是改變異味。繼續
map根據單個回傳值更改實作。”
如果提取if基于子句的資料并將它們作為基于物件的查找提供,則基于箭頭函式的映射器在一些擴展語法的幫助下可以歸結為簡單的東西,例如...
const createUrlItem = ({ resourceType, url }) => ({
url,
...(urlItemLookup[resourceType] ?? {}),
});
const resources = [{
resourceType: 'brand',
url: 'brandUrl',
}, {
resourceType: 'product',
url: 'productUrl',
}, {
resourceType: 'category',
url: 'categoryUrl',
}, {
resourceType: 'document',
url: 'documentUrl',
}];
const urlItemLookup = {
brand: {
changefreq: 'weekly',
priority: 0.9,
},
product: {
changefreq: 'monthly',
priority: 0.8,
},
document: {
changefreq: 'weekly',
priority: 0.6,
},
};
const urlModule = resources
.map(({ resourceType, url }) => ({
url,
...(urlItemLookup[resourceType] ?? {}),
}));
console.log({ urlModule, resources });
.as-console-wrapper { min-height: 100%!important; top: 0; }
如果一個人只想創建和收集新的 url 專案,每個專案都只有一個覆寫/現有的配置,reduce是首選的工具。基于查找的映射器實作被重構為一個reducer,然后可能看起來類似于下一個提供的代碼......
const resources = [{
resourceType: 'brand',
url: 'brandUrl',
}, {
resourceType: 'product',
url: 'productUrl',
}, {
resourceType: 'category',
url: 'categoryUrl',
}, {
resourceType: 'document',
url: 'documentUrl',
}];
const urlItemLookup = {
brand: {
changefreq: 'weekly',
priority: 0.9,
},
product: {
changefreq: 'monthly',
priority: 0.8,
},
document: {
changefreq: 'weekly',
priority: 0.6,
},
};
const urlModule = resources
.reduce((result, { resourceType, url }) => {
const config = urlItemLookup[resourceType];
if (config) {
result.push({ url, ...config });
}
return result;
}, []);
console.log({ urlModule, resources });
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
const resources = [{
resourceType: 'brand',
url: 'brandUrl'
}, {
resourceType: 'product',
url: 'productUrl'
}, {
resourceType: 'category',
url: 'categoryUrl'
}, {
resourceType: 'document',
url: 'documentUrl'
}];
const urlModule = [];
resources.forEach((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return urlModule.push({
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
});
}
if (resourceType === 'product') {
return urlModule.push({
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
});
}
if (resourceType === 'document') {
return urlModule.push({
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
});
}
});
console.log(urlModule);
uj5u.com熱心網友回復:
您必須在 forEach 回圈之外創建新陣列。
const urlModule = [];
resources.forEach(resource => {
const {resourceType} = resource;
if (resourceType === 'brand')
urlModule.push({url: `/${resource.url}`, changefreq: 'weekly', priority: 0.9})
if (resourceType === 'product')
urlModule.push({url: `/${resource.url}`, changefreq: 'monthly', priority: 0.8})
if (resourceType === 'document')
urlModule.push({url: `/${resource.url}`, changefreq: 'weekly', priority: 0.6})
})
uj5u.com熱心網友回復:
一種方法是在flatMap此處使用 a 。
它的作業原理類似于地圖,但您可以回傳零個或多個元素,而不必總是準確地回傳 1。
const urlModule = resources.flatMap((resource) => {
const { resourceType } = resource
if (resourceType === 'brand') {
return [{
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.9,
}]
}
if (resourceType === 'product') {
return [{
url: `/${resource.url}`,
changefreq: 'monthly',
priority: 0.8,
}]
}
if (resourceType === 'document') {
return [{
url: `/${resource.url}`,
changefreq: 'weekly',
priority: 0.6,
}]
}
return []
});
console.log(urlModule);
您也可以使用 afilter()后跟 a map()。
有很多方法可以解決這個問題。這取決于你喜歡哪個。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494012.html
