首页 > 解决方案 > 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());

标签: javascriptarraysstringclassoop

解决方案


用于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());


推荐阅读