[英]how to create a model in javascript to make sure all properties does exists
[英]how to make sure javascript check all properties
您好,我正在尝试检查联系人是否存在以及是否具有特定属性,然后将其返回
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 lookUp(firstName, prop) {
var i;
for (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";
} else if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop) === false) {
return "No such property";
}
}
}
lookUp("Harry", "likes");
问题在于,它仅返回循环中的第一个结果,因此在这种情况下,它将仅检查是否在contacts [0] firstName === firstName中,然后即使contacts [1] firstName === firstName返回false
尝试这个:
// Returns:
// contact prop if: contact with prop found
// true if: contact found, but not prop
// false if: not contact found
function lookUp(firstName, prop) {
var i, nameFound = false;
// Starts a loop that looks every contact until the list ends or until firstName with prop is found
for (i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName ) {
// If found, the function return the property "prop" of the contact named "firstName"
// Note that if there is 2 persons with the same name and both has prop, it returns the first one on the list
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
else{
nameFound = true;
}
}
}
// If the script reach this place, it's because the person wasn't found or was found but hasn't the prop
return nameFound;
}
function lookUp(firstName, prop) {
var i;
for (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";
}
要检查对象是否具有属性,您可以只检查if if(obj[prop])
。 我喜欢减少这种事情:
function lookUp (firstName, prop) {
return contacts.reduce(
function (found, contact) {
if (contact[prop] && contact.firstName === firstName)
found.push(contact);
return found;
}, []
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.