我一直在尝试使用以下代码解决此https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/问题:
function lookUpProfile(name, prop){
for (let a = 0; a < contacts.length; a++) {
if (contacts[a].firstName == name && contacts[a].hasOwnProperty(prop)) {
console.log(contacts[a][prop]);
}
else if (name != contacts[a].firstName) {
return "No such contact";
}
else {
return "No such property";
}
}
但是,此页面https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup提出以下建议,并且可以正常工作:
for (var 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";
我也尝试将以上内容修改为:
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name && contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
无济于事。
所以我的问题是,为什么我的代码不起作用?以及为什么需要使用嵌套的if语句而不是&&运算符?
感谢您的关注。
最佳答案
使用您创建的函数将始终返回:contacts[x][prop];
或"No such property"
,并且此行return "No such contact";
将永远不会执行,为什么?
通过嵌套两个if
语句,新的if
语句将返回:contacts[x][prop];
如果它验证为true
或"No such property"
如果它验证为false
,则此行将不再即使contacts[x].firstName === name
条件验证为false
,也可以执行/访问。这就是为什么要使用两个if
语句的原因:如果是"No such contact";
,则第一个返回false
(即使没有else
语句,因为如果第一个if
语句验证了以下内容,则不会执行任何操作)当然是false
,因此该函数跳到该if
语句后的下一行,即return "No such contact";
)
简单来说:即使"No such property"
是contacts[x].firstName === name
,您的函数也将返回falsy
。
这是一个片段说明:
// some dummy values just for the demo !
var contacts = [
{
firstName: "ths",
lastName: "sakh"
},
{
firstName: "firstname",
lastName: "lastname"
}
];
/**
* The modified function
**/
var r = (function test(name, prop) {
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name && contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
return "No such contact";
})("Wrong Name!", "firstName");
console.log('The modified function returned: "' + r + '" instead of return "No such contact"');
/**
* The original function
**/
var r = (function test(name, prop) {
for (var 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";
})("Wrong Name!", "firstName");
console.log('The original function returned: "' + r + '" and that\'s what should be returned.');
希望我能进一步推动您。
附言:请不要为
var r = (function(x, y){...}(arg1, arg2)
(aka IIFE
)语法(Immediately Invoked Function Expression)
惊慌。 Learn more关于它。