[英]Is there a way to iterate over objects in an array?
假設我有一個對象數組:
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
}
]
我正在嘗試迭代對象中的鍵和值
我嘗試使用 for 循環
function checker (name){
name = "";
for(i = 0; i < contacts.length; i++){
if(name === (contacts[i].firstName)){
return "yes" ;
}
else{
return "No such Contact";
}
}
}
checker("Harry");
使用參數“Harry”調用 function 應該為真並返回“yes”,而不是返回“No such contact”!
正如@Nicholas Tower 指出的那樣,您正在通過返回中斷循環執行。
因為你有一個對象數組,所以試試
contacts.find(contact => contact.name === nameYoureLookingFor)
Array.prototype.find() 將為您提供與條件匹配的第一個元素。 在這種情況下,object 必須包含具有給定值的屬性名稱。 object 是一個真實的值,所以你可以在這里使用單行
function checker(name){
return contacts.find(contact => contact.name === name) ? 'yes':'No such Contact';
}
name = "";
您將 name 重新分配給""
而不是使用函數的輸入值。
你基本上是在比較
"" === contacts[i].firstName
它將始終根據您的輸入數據使用else
語句。
嘗試這個:
var checker = (name) => {
contacts.forEach(item => {
if(item.firstName === name){
return console.log('Yes');
}else{
return 'No Match found'
}
})
}
有很多方法可以做到這一點。 正如@Nicholas Tower 所說,在您的示例中,只需將 else 返回移到循環之外就可以解決它:
function checker(name) {
for (let i = 0; i < contacts.length; i++) {
if(name === (contacts[i].firstName)){ return "yes" ; }
}
return "No such Contact";
}
checker("Harry");
您可以使用 for..of 循環以更簡潔的方式實現相同的目的:
function checker(name) {
for (let contact of contacts) {
if (name === contact.firstName) { return "yes" ; }
}
return "No such Contact";
}
checker("Harry");
...或發現:
function checker (name){
// will return the object if it exists, undefined if not
const contact = contacts.find((contact) => contact.firstName === name);
// convert to a boolean and return the 'yes' if truthy (the object), 'No such Contact' if falsy (the undefined)
return !!contact ? 'yes' : 'No such Contact';
}
checker("Harry");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.