已經為我預先撰寫了一個將名稱和屬性 (prop) 作為引數的lookUpProfile 函式。
如果兩者都為真,則回傳該屬性的“值”。
如果姓名不對應任何聯系人,則回傳字串 No such contact。
如果 prop 不對應于找到匹配名稱的聯系人的任何有效屬性,則回傳字串 No such property。
如果我使用 && 而不是嵌套的 if 陳述句,為什么它不起作用
// Setup
const 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(name, prop) {
// Only change code below this line
for (let i = 0; i <= contacts.length; i ) {
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else return "No such contact";
}
return "No such contact";
// Only change code above this line
}
lookUpProfile("Akira", "likes");
function lookUpProfile(name, prop) {
for (let x = 0; x < contacts.length; x ) {
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
uj5u.com熱心網友回復:
function lookUpProfile(name, prop) {
// Only change code below this line
for (let i = 0; i <= contacts.length; i ) {
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else return "No such contact";
}
return "No such contact";
// Only change code above this line
}
如果 contacts[0] 不是您想要獲取的值,此函式將始終回傳“No such contact”。
下面的代碼將起作用。
function lookUpProfile(name, prop) {
// Only change code below this line
for (let i = 0; i <= contacts.length; i ) {
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
}
return "No such contact";
// Only change code above this line
}
uj5u.com熱心網友回復:
問題是這些行
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else return "No such contact";
您基本上是在說如果給定的條件不匹配,則回傳帶有'No such contact'. 這意味著回圈在第一次迭代后停止迭代。現在由于回傳函式,回圈結束意味著您只檢查第一個索引,即[0]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409520.html
標籤:
上一篇:將json資料轉換為物件
