[英]Javascript - Unable to change object value in array
我有以下對象數組。 每個對象都包含朋友的姓名、年齡和性別,如下所示:
var friends = [{name: "Dan",
age: 34,
gender: "male"},
{name: "Chris",
age: 30,
gender: "male"},
{name: "Laura",
age: 32,
gender: "female"}];
我必須編寫一個函數,可以將三個朋友中的任何一個添加到他們的年齡中。 我寫過這個:
function hasBirthday(name){
friends.forEach(function(person){
if(name === person.name){
person.age += 1;
}
}); return person.age;
}
假設我想將 Laura 的年齡從 32 更改為 33。我會這樣調用函數:
hasBirthday("Laura");
如果我將該函數分配給一個變量,然后使用 console.log 它,我希望輸出為 33。但是,我總是收到以下錯誤消息:
ReferenceError: person is not defined.
任何人都可以解釋為什么我不斷收到此錯誤消息? 我完全被難住了。 謝謝。
只需刪除return person.age;
function hasBirthday(name){
friends.forEach(function(person){
if(name === person.name){
person.age += 1;
}
});
// return person.age;
}
hasBirthday("Laura"); //Laura has 33 now
如果您還需要hasBirthday("Laura")
的新時代,請像這樣修改。
function hasBirthday(name){
var new_age = 0;
friends.forEach(function(person){
if(name === person.name){
person.age += 1;
new_age = person.age;
}
});
return new_age;
}
alert(hasBirthday("Laura")); //Laura has 33 now
想想如果你有兩個“勞拉”,函數只返回最后一個匹配。 此外,當 person 不存在時,函數返回 0。
您正在將 person.age 返回到 forEach 循環的范圍之外。 為了解決這個問題,您可以聲明一個變量,該變量可以跟蹤您詢問的朋友的年齡。 您還可以通過當前元素的索引更改朋友數組中的年齡。
var friends = [{name: "Dan",
age: 34,
gender: "male"},
{name: "Chris",
age: 30,
gender: "male"},
{name: "Laura",
age: 32,
gender: "female"}];
function hasBirthday(name){
var current_age = 0;
friends.forEach(function(person, i){
if(name === person.name){
current_age = person.age + 1;
friends[i].age = current_age; // you can update the global array as well.
}
});
return current_age;
}
hasBirthday("Laura");
console.log(friends);
你沒有給年齡加+1。 您必須比較姓名並在該人的年齡上加 +1
function hasBirthday(name){ friends.forEach(function(person){ if(name === person.name){ person.age += 1; }return person.age; }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.