![](/img/trans.png)
[英]JavaScript: How do I add a custom class object as a key of an array
[英]How do I update a JavaScript class object that is an array?
我是面向對象編程的新手,我遇到了一個需要解決的問題,我需要創建一個具有屬性和功能的 JavaScript class。 其中一個屬性是存儲多個字符串的字符串數組。 object 實例化如下:
let person = new Person('Bob', 30, 'Male', ['hunting', 'the gym', 'photography']);
output 應該是:你好,我叫 Bob,我的性別是男性,我 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);
我了解如何更新其他屬性,但我堅持如何更新數組屬性。 請幫忙。
為什么不將數組視為常規參數?
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.