![](/img/trans.png)
[英]Iterate over all Array indexes within array with map method Javascript
[英]includes function Iterate over all array in javascript
我有一個代碼,它遍歷一個對象數組並檢查它是否包含管理員字。如果它包含,那么我想調用管理員 API,如果沒有,那么我想調用非管理員 API。 代碼工作正常,但問題是在迭代時說權限包含 5 個對象,第三個索引包含 admin 關鍵字,然后邏輯調用 2 個非管理員 api 和 1 個管理員 api,然后再調用 2 個非管理員 api。 有沒有更好的方法來編寫邏輯將檢查整個數組是否包含 admin 關鍵字並僅調用一次 admin API 或 Non-Admin API 的代碼。
if (tempAuth && tempAuth.length > 0) {
this.auth = tempAuth.filter(x => {
if (x.authority.includes('admin')) {
// Admin API
this.getalldetails();
}
else {
// Non Admin API
this.getUserdetails();
}
});
一種選擇是使用some
方法檢查是否滿足身份驗證條件。 然后您可以使用該 boolean 值來確定下一步要做什么。
if (tempAuth && tempAuth.length > 0) {
this.auth = tempAuth.some(x => x.authority.includes('admin'));
if (this.auth) {
this.getalldetails();
} else {
this.getUserdetails();
}
}
您可以使用some()
方法來確定數組tempAuth
中的至少一個元素是否包含管理員authority
。 如果是,那么我們將getalldetails
設置為this.auth
否則我們傳遞getUserdetails
if (tempAuth && tempAuth.length > 0) {
var found = tempAuth.some(x => x.authority.includes('admin'));
this.auth = found ? this.getalldetails() : this.getUserdetails();
}
如果至少一項條件為真,則數組 function some
返回 boolean。
if (tempAuth && tempAuth.length > 0) {
const isAdmin = tempAuth.some(x => x.authority.includes('admin'));
if (isAdmin) {
// Admin API
this.getalldetails();
} else {
// Non Admin API
this.getUserdetails();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.