【问题标题】:Javascript Add Element To Array At Specific Index and Remover "Join" SeparatorJavascript在特定索引处将元素添加到数组并去除“加入”分隔符
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 难以置信的答案。非常感谢。
    • 不客气 :)
    【解决方案2】:

    这是满足您需要的一种方法。

    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() {
        let interestsString = this.interests.join(', ').replace(/, ([^,]*)$/, ' and $1')
        console.log(interestsString);
      }
    }
    
    let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);
    
    console.log(person1.bio());

    【讨论】:

    • 有趣的解决方案。我还没有对 Regex 代码了解太多,所以我将对其工作原理进行一些研究。谢谢!
    【解决方案3】:

    当你像这样使用拼接时

     this.interests.splice(index, 0, conjunction)
    

    您将元素添加到数组中,然后连接函数添加了另一个“,” 最好只更改它自己的元素并将 and 添加到它。

    像这样:

        let changeTo = conjunction + this.interests[index];
        this.interests.splice(index, 1, changeTo);
    

    【讨论】:

    • 聪明的解决方法,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2015-11-21
    • 2012-07-23
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多