You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript拼接数组时在末尾元素前加and如何消除多余逗号

解决方案

问题原因

  • 你把" and"作为独立元素插入数组后,调用join(', ')时会在所有相邻元素之间统一添加逗号,所以"and"前后都会被加逗号,自然出现多余的逗号。
  • 另外你当前的写法有隐藏缺陷:直接用splice修改了实例的interests原数组,多次调用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() {
    // 先拷贝原数组,避免修改实例属性
    const interestsCopy = [...this.interests];
    let interestsString = '';
    const len = interestsCopy.length;
    if (len === 1) {
      interestsString = interestsCopy[0];
    } else if (len === 2) {
      interestsString = interestsCopy.join(' and ');
    } else {
      // 取出最后一个元素,前面的用逗号拼接,最后加 and 和最后一个元素
      const lastItem = interestsCopy.pop();
      interestsString = `${interestsCopy.join(', ')}, and ${lastItem}`;
    }
    console.log(interestsString);
    return interestsString;
  }
}

let person1 = new Person('test', 'test', '29', 'Male', ['skiing', 'cooking', 'gardening']);
person1.bio(); // 输出:skiing, cooking, and gardening

如果不需要牛津逗号(也就是"and"前面不需要逗号),只需要把拼接的逻辑改成${interestsCopy.join(', ')} and ${lastItem}即可。

内容的提问来源于stack exchange,提问作者Mickey Vershbow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:30:03