简体   繁体   中英

How do I update a JavaScript class object that is an array?

I am new to object-oriented programming and I have been given a problem to solve where I need to create a JavaScript class with attributes and functions. One of the attributes is an array of strings that stores multiple strings. The object instantiation is as follows:

let person = new Person('Bob', 30, 'Male', ['hunting', 'the gym', 'photography']);

The output should be: Hello, my name is Bob, my gender is male and I am 30 years old. My interests are hunting, the gym and photography.

Here is what I have done so far:

class Person
{
    static name;
    static age;
    static gender;
    static interests = [];

    constructor(name, age, gender)
    {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.interests = addInterests();
    }
    hello(){
        return "Hello, my name is " + this.name + " my gender is " + this.gender + " and I am " + this.age + " years old. My interests are " + this.interests + " .";
    }
    addInterests()
    {
        for(let i = 0; i < arguments.length; i++)
        {
            interests.push(arguments[i]);
        }
    }
}

let person = new Person('Ryan', 30, 'male',['being a hardarse', 'agile', 'ssd hard drives']);
let greeting = person.hello();
console.log(greeting);

I understand how to update the other attributes but I'm stuck on how to update the array attribute. Please help.

Why don't you just treat the array as a regular argument?

class Person
{
    static name;
    static age;
    static gender;
    static interests = [];

    constructor(name, age, gender, interests)
    {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.interests = interests;
    }
    hello(){
       return "Hello, my name is " + this.name + " my gender is " + this.gender + " and I am " + this.age + " years old. My interests are " + this.interests
    }
}

let person = new Person('Ryan', 30, 'male',['being a hardarse', 'agile', 'ssd hard drives']);
let greeting = person.hello();
console.log(greeting)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM