javascript - Javascript将元素添加到特定索引处的数组并去除“加入”分隔符
问题描述
我知道这个问题已经被问过很多次,但我找不到解决我的具体问题的方法。我猜我需要完全重构我的代码,但可以使用一些指导。
我正在用 Javascript 练习 OOP。我想加入一个数组并在最后一个元素之前添加一个“and”连词。这样 [1, 2, 3] ==> "1, 2, 和 3"。
我在下面的注释中包含了我的代码。正如您将看到的,我得到的当前输出是“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());
解决方案
用于Intl.ListFormat()
在处理分隔符和连词时将列表转换为字符串:
const listFormatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
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() {
return listFormatter.format(this.interests);
}
}
let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);
console.log(person1.bio());
另一种选择是使用数组操作 - 如果数组只包含一个项目,则返回该项目。如果它包含多个项目,则创建一个包含所有原始项目的新数组,但最后一个,以及在添加“and”后返回的最后一个项目。加入阵列。
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() {
return this.interests.length > 1 // if there are multiple items
?
[
...this.interests.slice(0, -1), // get all items but the last
`and ${this.interests.at(-1)}` // add the last item with "and"
].join(', ') // join
:
this.interests.at(0); // just take the single existing item
}
}
let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);
console.log(person1.bio());
推荐阅读
- node.js - 嵌套元素中的 Geo JSON (Mongoose)
- azure-web-app-service - .Net 5 Api System.NotSupportedException:不支持“System.Type”实例的序列化和反序列化
- lda - “解压的值太多(预期为 2)”错误
- wpf - 在 WPF 中将 CMYK tif 图像打印到 CMYK pdf 会失去颜色
- google-chrome-extension - 更新服务工作者的本地存储,Chrome 扩展
- java - 删除文档文件后 takePersistableUriPermission 访问丢失
- kotlin - 带有主管的 Kotlin-Coroutines 多次启动失败
- verilog - 我想添加一个检查器,当启用为“1”时检查 clk 是否正在切换。clk 的频率是随机的(未知)
- sql - 出乎意料 ORA-00923
- c++ - 创建一个 `property` 类来支持不同于模板类型参数的一般隐式转换