【发布时间】:2021-11-26 02:09:48
【问题描述】:
我知道这个问题已被问过很多次,但我找不到解决我的具体问题的方法。我猜我需要完全重构我的代码,但可以使用一些指导。
我正在用 Javascript 练习 OOP。我想加入一个数组并在最后一个元素之前添加一个“and”连词。这样 [1, 2, 3] ==> "1, 2, and 3"。
我在下面的 cmets 中包含了我的代码。正如您将看到的,我得到的当前输出是“1、2 和 3”。我怎样才能摆脱多余的逗号?我是不是走错路了?
class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first: first,
last: last,
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first} ${this.name.last}.`)
}
bio() {
// store the index of the last element of the array in a variable called index
let index = this.interests.length - 1;
// store the conjunction for end of array
let conjunction = " and"
// insert the conjunction before last element in array
this.interests.splice(index, 0, conjunction)
// join the array into a string separated by commas
let interestsString = this.interests.join(", ");
console.log(interestsString);
}
}
let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);
console.log(person1.bio());
【问题讨论】:
标签: javascript arrays string class oop