簡體   English   中英

JavaScript中的嵌套循環

[英]Nesting loops in javascript

我認為以下代碼是正確的:

該函數應檢查firstName是否是實際聯系人的firstName,並且給定屬性(prop)是該聯系人的屬性。

如果兩者都為真,則返回該屬性的“值”。

使用參數“ Kristian”和“ lastName”對函數lookUpProfile的調用應返回值“ Vos”,但不是。

有些想法哪里錯了?

 var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number": "0543236543", "likes": ["Pizza", "Coding", "Brownie Points"] }, { "firstName": "Harry", "lastName": "Potter", "number": "0994372684", "likes": ["Hogwarts", "Magic", "Hagrid"] }, { "firstName": "Sherlock", "lastName": "Holmes", "number": "0487345643", "likes": ["Intriguing Cases", "Violin"] }, { "firstName": "Kristian", "lastName": "Vos", "number": "unknown", "likes": ["Javascript", "Gaming", "Foxes"] } ]; function lookUpProfile(firstName, prop){ for(var i=0;i<contacts.length;i++){ for(var j=0;j<contacts[i].length;j++){ if(contacts[i][0]===firstName && contacts[i][j].hasOwnProperty(prop)){ return contacts[i][j]; } } } } // Change these values to test your function lookUpProfile("Kristian", "lastName"); 

您的代碼存在的問題是,第二個for循環正在檢查根本不存在的屬性contacts[i].length 對象沒有.length屬性,只有數組。

您不需要第二個for循環即可循環所有屬性,只需檢查firstName,然后檢查所需的屬性是否存在,然后將其返回即可。

for(var i=0;i<contacts.length;i++){ if(contacts[i]['firstName']===firstName && contacts[i].hasOwnProperty(prop)){ return contacts[i][prop]; } }

應該是你想要的。


如果要循環所有對象屬性,應使用for in循環,如下所示:

for(var key in contacts[i]){ //place your check here using contacts[i][key] the get the value for the key }

編輯:增加了for in例如

您僅可以在lookup-function中使用兩行代碼來解決問題:

function lookUpProfile(firstName, prop) {
  var contact = contacts.find((c) => c.firstName === firstName);
  return contact.hasOwnProperty(prop) ? contact[prop] : null;
}

用我的JSFiddle嘗試一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM