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

ECMA6实现多单词按$分隔拼接,如何补全Add类的print方法?

ES6规范下print方法实现方案

完整可运行代码

class Add {
  constructor(...words) {
    this.words = words;
  }
  // 新增符合要求的print方法
  print() {
    // 写法1:可读性更高
    const output = `$${this.words.join('$')}$`;
    console.log(output);

    // 写法2:代码更简洁,可替换上面两行代码使用
    // console.log(['', ...this.words, ''].join('$'));
  }
}

var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");
var y = new Add("this", "is", "awesome");
var z = new Add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit");

x.print();
y.print();
z.print();

逻辑说明

  • 构造函数已经将传入的所有单词存入this.words数组,直接调用数组方法处理即可
  • 核心逻辑是把所有单词用$分隔,同时首尾各补充一个$,上述两种写法均符合ES6规范
  • 最终在print方法内直接打印处理完成的字符串即可

运行输出结果

$hehe$hoho$haha$hihi$huhu$
$this$is$awesome$
$lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$

内容的提问来源于stack exchange,提问作者RK Eshat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:36:00