我想创建一个迭代数组的函数,该数组包含具有名称,姓氏和年龄属性的单独对象。该函数应该使用参数“name”并在控制台中返回名称,姓氏和年龄。
我该怎么做?我已经看了一些其他的问题,但似乎无法弄清楚如何做到这一点。到目前为止我创造了这个......
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
// code here
}
person(sue)
答案 0 :(得分:2)
只需使用Array#find()
method,就像这样:
var people = [{
name: "Sue",
surname: "Beckett",
age: 50
},
{
name: "Bill",
surname: "Borough",
age: 44
},
{
name: "Janet",
surname: "Jupp",
age: 23
},
{
name: "Peter",
surname: "Pepper",
age: 21
},
{
name: "Samantha",
surname: "Salad",
age: 17
}
];
function person(name) {
return people.find(function(p) {
return p.name == name;
});
}
console.log(person("Samantha"));
console.log(Object.values(person("Samantha")));
<强>演示:强>
string
注意:强>
sue
传递,只传递""
而不sue
将假设您有一个名为Object.values()
的变量。console.log(Object.values(person("Samantha")));
仅显示值
对象属性,而不是整个对象。简单地写一下:
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
for (var key in people) {
var person = people[key];
if (name === person.name) {
console.log(person);
}
}
}
person("Sue"); // string always needs quotes: " or ' character
答案 1 :(得分:0)
SELECT * FROM posts where id in (friendsIds)
答案 2 :(得分:0)
使用filter
:
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(personName) {
var user = people.filter(function (user) {
return (user.name.toLowerCase() == personName.toLowerCase());
});
return user[0] !== undefined ? user[0] : 'not found';
}
console.log(person('sue'));
答案 3 :(得分:0)
您可以通过检查name
属性和name
变量的小写值来过滤数组。
function person(name) {
people
.filter(o => o.name.toLowerCase() === name.toLowerCase())
.forEach(({ name, surname, age}) => {
console.log('name:', name);
console.log('suname:', surname);
console.log('age:', age);
});
}
var people = [{ name: "Sue", surname: "Beckett", age: 50 }, { name: "Bill", surname: "Borough", age: 44 }, { name: "Janet", surname: "Jupp", age: 23 }, { name: "Peter", surname: "Pepper", age: 21 }, { name: "Samantha", surname: "Salad", age: 17 }];
person('sue');
&#13;
答案 4 :(得分:-1)
var people = [
{ name: "Sue", surname: "Beckett", age: 50},
{ name: "Bill", surname: "Borough", age: 44},
{ name: "Janet", surname: "Jupp", age: 23},
{ name: "Peter", surname: "Pepper", age: 21},
{ name: "Samantha", surname: "Salad", age: 17}
];
function person(name) {
people.map((data,index)=>{
if(data.name == name)
{
console.log(data.name);
console.log(data.surname);
console.log(data.age);
return;
}
})
}
person("Sue");