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
相关产品推荐
相关产品推荐

