![](/img/trans.png)
[英]Transpile forEach, map, filter and for of to length based for loop in JavaScript
[英]Better solution for forEach and if ? map, filter Javascript
對於這個邏輯,我真的需要更好的解決方案:
this.allClients.forEach(obj => {
if(obj.status === 2) {
this.numOfWaitingUsers.push(obj)
}
if(obj.status === 1) {
this.numOfInactiveUsers.push(obj)
}
if(obj.status === 0) {
this.numOfActiveUsers.push(obj)
}
if(obj.status === 3) {
this.numOfAClosedUsers.push(obj)
}
})
這是完美的工作,但我需要更好的解決方案。 我知道用更少的代碼可以做得更好。
一種解決方案是 map 從狀態編號到數組屬性名稱,如下所示:
const arrayNameByStatus = { // This could be an array, but I wasn't sure if
0: "numOfActiveUsers", // status codes were necessarily contiguous like
1: "numOfInactiveUsers", // they are in the question
2: "numOfWaitingUsers",
3: "numOfAClosedUsers",
};
for (const obj of this.allClients) {
const name = arrayNameByStatus[obj.status];
if (name) { // Remove this for an error if status is an unexpected value
this[name].push(obj);
}
}
現場示例:
const arrayNameByStatus = { 0: "numOfActiveUsers", 1: "numOfInactiveUsers", 2: "numOfWaitingUsers", 3: "numOfAClosedUsers", }; class Example { constructor() { this.allClients = [ {status: 0}, {status: 2}, {status: 2}, ]; this.numOfActiveUsers = []; this.numOfInactiveUsers = []; this.numOfWaitingUsers = []; this.numOfAClosedUsers = []; } method() { for (const obj of this.allClients) { const name = arrayNameByStatus[obj.status]; if (name) { this[name].push(obj); } } } } const e = new Example(); e.method(); console.log(e);
但是,如果您要定期按狀態索引,則可以考慮更改 object 的結構以直接支持它。 例如,您可能有一個userCounts
屬性,它是一個 object,鍵為 0 到 3,它可以讓您直接索引:
// **IF** you change the structure so that `this` has a `userCounts`
// keyed by status:
for (const obj of this.allClients) {
const array = this.userCounts[obj.status];
if (array) { // Remove this for an error if status is an unexpected value
array.push(obj);
}
}
現場示例:
class Example { constructor() { this.allClients = [ {status: 0}, {status: 2}, {status: 2}, ]; this.userCounts = { 0: [], 1: [], 2: [], 3: [], }; } method() { for (const obj of this.allClients) { const array = this.userCounts[obj.status]; if (array) { array.push(obj); } } } } const e = new Example(); e.method(); console.log(e);
老實說,您發布的代碼看起來非常好。 但是,如果你有更多的if
語句到 go ,你可以像下面這樣優化它:
// use the corresponding status as the key to access each array
let dataContainer = {
0: this.numOfActiveUsers,
1: this.numOfInactiveUsers,
2: this.numOfWaitingUsers,
3: this.numOfAClosedUsers
}
this.allClients.forEach(obj => dataContainer[obj.status].push(obj))
為您的狀態代碼使用查找表:
// const countNames = {0:"numOfActiveUsers", 1:"numOfInactiveUsers", 2:"numOfWaitingUsers", 3:"numOfAClosedUsers"};
const countNames = ["numOfActiveUsers", "numOfInactiveUsers", "numOfWaitingUsers", "numOfAClosedUsers"];
for (const obj of this.allClients) {
const count = countNames[obj.status];
if (count)
this[count].push(obj)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.