gpt4 book ai didi

javascript - 循环遍历数组,但即使 “else” 语句为 true 也执行 “if” 语句 (javascript)

转载 作者:行者123 更新时间:2023-12-03 06:35:07 25 4
gpt4 key购买 nike

在循环中我不确定我是否犯了错误或错误的代码。当我单独运行 if 语句时,它有效。但是当我与“else if”语句一起运行它时。 if 语句失败,else if 语句有效,即使第一个 if 语句为 true。

https://www.freecodecamp.com/challenges/profile-lookup

//Setup
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){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
if ( contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop) ) {
return contacts[i][prop];


} else if( contacts[i].firstName !== firstName ) {
return "No such contact";
}
}
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

最佳答案

将“没有这样的联系人”回复移到循环之外:

function lookUpProfile(firstName, prop) {
var match = false;
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName) {
match = true;
var valid = contacts[i].hasOwnProperty(prop);
}
if (match && valid) {
return contacts[i][prop];
}
if (match && !valid) {
return "No such property";
}
}
return "No such contact";
}

假设:每个人存储在一张卡中。

这段代码会迭代所有联系人,当当前联系人符合条件时,会立即返回。当循环结束时,表示没有匹配到的联系人,因此返回相应的回复。

我更喜欢这种没有嵌套 if 的编码方式,但您可以重写内部 for 代码,如下所示:

if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}

关于javascript - 循环遍历数组,但即使 “else” 语句为 true 也执行 “if” 语句 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com