Javascript - 无法更改数组

时间:2017-10-05 19:18:19

标签: javascript arrays object

我有以下对象数组。每个对象都包含朋友的姓名,年龄和性别,如下所示:

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;
}

让我们说我想将劳拉的年龄从32岁改为33岁。我这样称呼这个职能:

hasBirthday("Laura");

如果我将函数分配给变量然后调用console.log,我希望输出为33.但是,我总是收到以下错误消息:

ReferenceError: person is not defined.

有人能说清楚为什么我一直收到此错误消息吗?我完全难过了。感谢。

3 个答案:

答案 0 :(得分:-1)

只需删除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

想想你是否有两个"劳拉",功能只返回最后一场比赛。此外,当人不存在时,函数返回0。

答案 1 :(得分:-3)

您没有为年龄添加+1。您必须比较名称并为该人的年龄添加+1

...
2017-10-05T19:09:48.0651172Z [SYSTEM] --> [release]
2017-10-05T19:09:48.0651172Z [PRODBUILDNUMBER] --> [$(Release.Artifacts.Prod - myproject - build.BuildNumber)]
2017-10-05T19:09:48.0651172Z [RELEASE_RELEASEID] --> [114]
...

答案 2 :(得分:-3)

您将返回person.age超出forEach循环的范围。要解决此问题,您可以声明一个可以跟踪您询问的朋友年龄的变量。您还可以通过当前元素的索引更改friends数组中的年龄。

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);