简体   繁体   English

如何更新作为数组的 JavaScript class object?

[英]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.我是面向对象编程的新手,我遇到了一个需要解决的问题,我需要创建一个具有属性和功能的 JavaScript class。 One of the attributes is an array of strings that stores multiple strings.其中一个属性是存储多个字符串的字符串数组。 The object instantiation is as follows: object 实例化如下:

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. output 应该是:你好,我叫 Bob,我的性别是男性,我 30 岁。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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