我創建了一個通過查詢器創建的動態物件陣列。但我無法弄清楚如何訪問陣列中的特定物件編輯:這是控制臺記錄我的陣列的方式
例如,我如何訪問第二工程師 (Mark)?
請記住,陣列將根據用戶輸入而變化
team = [
Manager {
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5'
},
Engineer {
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
Engineer {
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
Engineer {
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
}
Intern {
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
uj5u.com熱心網友回復:
使用find方法。如果沒有這樣的標記,則find回傳 null。
如果你想找到工程師馬克
const result = data.find(x => {
return x instanceof Engineer && x.name === 'Mark'
})
[更新] 如果你想找第二個工程師
const result = data.filter(x => {
return x instanceof Engineer
})[1]
uj5u.com熱心網友回復:
正如Sepehr jozef提到的,結構不是那么方便。如果我們采用他的結構,您可以通過.find方法找到它。
var team = [
{
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
const mark = team.find(function(teamMember){
return teamMember.name === "Mark";
})
變數“mark”現在包含工程師“Mark”的物件。
uj5u.com熱心網友回復:
首先,你的結構是錯誤的。
它應該是:
var team = [
{
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
并獲得標記(2)你應該使用:
team[3].name
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342664.html
