[英]Syntax error Javascript foreach
好的,我是Java開發人員(新)。 我試圖找出Javascript。 和React,這就是為什么我有“ this.props”,它來自減速器的原因。
我有一個ID為ID的對象。 以及一個具有ID和名稱的帳戶數組。 我只想將每個帳戶數組ID與對象ID進行比較,然后返回帳戶名稱。 簡單吧? 顯然不適合我。 我收到語法錯誤,我真的不知道我在做什么錯...
getName = object => {
const objectId = object.id;
const name = this.props.accounts.foreach(account => (
if (account.id === objectId)
return this.account.name;
)
)
return name;
}
編輯:謝謝大家! 我已經將“()”更改為“ {}”,並將this.account.name更改為account.name。 而且有效! 我沒有看到那個錯誤
您在傳遞給foreach
的回調函數中使用括號而不是括號
getName = object => {
const objectId = object.id;
const name = this.props.accounts.foreach(account => {
if (account.id === objectId)
return this.account.name;
}
)
return name;
}
這只是一個小錯誤。 每當執行代碼塊時,它都應該位於{}中,而不是()中。 就像Java或大多數編程語言一樣。
getName = object => {
const objectId = object.id;
const name = this.props.accounts.foreach(account => {
if (account.id === objectId)
return this.account.name;
}
)
return name;
}
更換
return this.account.name;
至
return account.name;
如,
const name = this.props.accounts.foreach(account => {
if (account.id === objectId)
return account.name;
})
因為這是指道具而不是說明。 由於在forEach的參數中有帳戶對象,因此您可以直接訪問名稱。
它是語法錯誤。 考慮使用能夠捕獲此類錯誤的編輯器/ IDE。 注釋了需要在代碼中進行哪些更改:
getName = object => {
const objectId = object.id;
const name = this.props.accounts.foreach(account => ( // should be {
if (account.id === objectId)
return this.account.name;
) // should be }
)
return name;
}
在forEach
您傳遞了一個函數,並且函數主體要求使用大括號{}
,而不是括號()
。 您一切都很好,唯一的問題是括號。 您的代碼應如下所示:
const name = this.props.accounts.foreach(account => {
if (account.id === objectId)
return account.name;
})
PS:您也可以使用filter
代替forEach
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.