返回的地方是朋友[i]?
返回的地方是朋友[i]?
返回的地方是朋友[i]?
var friends = {
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "(831)524-2213",
address: ["531 Recht St.","Hollister","CA","95037"]
},
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(831)524-0349",
address: ["310 E Dunne Ave", "Morgan Hill", "CA","95037"]
}
};
var search = function(name){
for (var i=0;i<friends;i++){
if (friends[i].firstName === name) {
console.log(friends[i]);
return friends[i];
}
}
};
答案 0 :(得分:1)
问题是朋友是一个对象而不是一个数组所以你的循环是错误的
如果您想将friends
作为对象本身,那么您需要迭代该对象的属性
var search = function (name) {
for (var key in friends) {
if (friends.hasOwnProperty(key) && friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
演示:Fiddle
或者使用数组
var friends = [{
firstName: "Steve",
lastName: "Jobs",
number: "(831)524-2213",
address: ["531 Recht St.", "Hollister", "CA", "95037"]
}, {
firstName: "Bill",
lastName: "Gates",
number: "(831)524-0349",
address: ["310 E Dunne Ave", "Morgan Hill", "CA", "95037"]
}];
var search = function (name) {
for (var i = 0; i < friends.length; i++) {
if (friends[i].firstName === name) {
console.log(friends[i]);
return friends[i];
}
}
};
演示:Fiddle