gpt4 book ai didi

javascript - 嵌套 if 语句 - 如何重构条件以在迭代时使用一个 if 语句

转载 作者:行者123 更新时间:2023-11-30 08:19:12 27 4
gpt4 key购买 nike

我有一个对象数组:

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(name, prop) {  

for ( i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop]
} else {
return "No such property";
}
}
}

return "No such contact";

}

console.log(lookUpProfile("Harry", "likes"));

我试图重构函数,因此我可以使用一个 if 语句和 AND 运算符,而不是使用两个嵌套的 if 语句。为什么我这样做是为了提高可读性,因为我发现嵌套的 ifs 很难阅读。当我这样做时,我没有得到预期的返回值——当对象确实存在时,我得到“没有这样的属性”。那么换句话说,为什么第二个功能不能正常工作?我是否打破了函数迭代的方式?

function lookUpProfile(name, prop) {  

for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop]
} else {
return "No such property";
}
}
return "No such contact";
}

console.log(lookUpProfile("Harry", "likes"));

最佳答案

这里的问题是您要尝试做两件事。

  1. 根据名字从数组中找到正确的对象。
  2. 确定该对象是否具有特定属性,如果有则返回其值。

为此,有一个嵌套的 if 是有意义的。 2 位逻辑,2 个 if 语句。

你当然可以将它重构为不使用嵌套 ifs,首先尝试找到对象,然后检查该对象是否具有所需的属性:

function lookUpProfile(name, prop) {  
var obj = contacts.find(c => c.firstName === name);
if(!obj)
return "No such contact";

if(obj.hasOwnProperty(prop))
return obj[prop];

return "No such property";
}


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"]
}
];


console.log(lookUpProfile("Harry", "likes"));
console.log(lookUpProfile("Harry", "foo"));
console.log(lookUpProfile("Bob", "likes"));

关于javascript - 嵌套 if 语句 - 如何重构条件以在迭代时使用一个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56903834/

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