數組對象的屬性名稱和屬性值的提取_學習案例

來源:互聯網
上載者:User

<span style="font-family: 'Microsoft YaHei'; line-height: 18.1818px; white-space: pre-line; background-color: rgb(255, 255, 255);">有一個對象數組,裡面儲存著通訊錄。</span>

函數 lookUp 有兩個參數: firstName 和prop 。

函數將會檢查通訊錄是否存在 firstName值 和 prop 屬性。

如果它們都存在,函數返回prop屬性對應的值。

如果firstName 值不存在,返回"No such contact"。

如果prop 屬性不存在,返回"No such property"。

//Setupvar 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 lookUp(firstName, prop){  for (var i in contacts)  {if (contacts[i].firstName === firstName && prop in contacts[i])     return contacts[i][prop];}  for ( i in contacts)  {  if (prop in contacts[i] ===false)     return  "No such property";    }  for ( i in contacts)  {  if (contacts[i].firstName !== firstName)     return "No such contact";}  }// Change these values to test your functionlookUp("Akira", "address");

關於屬性名稱和屬性值:
在這個案例中,contacts[i].firstName 指的是屬性值,prop in contacts[i]提取的是屬性名稱,由於是嵌套數組形式({[屬性名稱:值],[屬性名稱:值]},所以需要添加i,遍曆i組的屬性名稱和屬性值。


以下方法轉自某網友的代碼,使用hasOwnProperty:是用來判斷一個對象是否有你給出名稱的屬性或對象。不過需要注意的是,此方法無法檢查該對象的原型鏈中是否具有該屬性,該屬性必須是對象本身的一個成員。

<span style="font-family:Microsoft YaHei;">for(var i=0;i<contacts.length;i++){if(contacts[i].firstName==firstName){if(contacts[i].hasOwnProperty(prop)){return contacts[i][prop];}else{return "No such property";}}}return "No such contact";</span>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.