【问题标题】:How do I update a JavaScript class object that is an array?如何更新作为数组的 JavaScript 类对象?
【发布时间】:2022-01-03 19:09:55
【问题描述】:

我是面向对象编程的新手,我遇到了一个需要解决的问题,我需要创建一个带有属性和函数的 JavaScript 类。其中一个属性是存储多个字符串的字符串数组。对象实例化如下:

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

输出应该是: 你好,我的名字是鲍勃,我的性别是男性,我今年 30 岁。我的兴趣是打猎、健身和摄影。

这是我到目前为止所做的:

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

我了解如何更新其他属性,但我不知道如何更新数组属性。请帮忙。

【问题讨论】:

  • "arguments 是一个类似数组的对象,可在函数内部访问,其中包含传递给该函数的参数值。"跨度>
  • 您没有使用 arguments 作为数组,因为您将数组作为参数传递。如果您想像这样使用arguments,请像let person = new Person('Bob', 30, 'Male', 'hunting', 'the gym', 'photography'); 一样调用Person,然后只使用第四个参数。当然,您应该研究一下rest parameters 以使其更容易。
  • @HereticMonkey 它甚至不是一个休息论点——它只是一个正常的论点。 constructor(name, age, gender) -> constructor(name, age, gender, interests) 然后this.interests = addInterests(); -> this.interests = interestes;
  • @VLAZ 我很清楚。我说如果示例构造函数是首选的构造方法,OP 应该研究剩余参数以使过程更容易。

标签: javascript arrays class oop


【解决方案1】:

你为什么不把数组当作一个常规参数呢?

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2021-11-27
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多