This is an assingment from SoloLearn.
The idea is to add a string to all elements in an array, where each element is separated by a dollar sign $. The output should be as below
$hehe$hoho$haha$hihi$huhu$ $this$is$awesome$ $lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$
The way I tried is wrong, since after each element should be only one string, but the output for my code is
$hehe$$hoho$$haha$$hihi$$huhu$ $this$$is$$awesome$ $lorem$$ipsum$$dolor$$sit$$amet$$consectetur$$adipiscing$$elit$
My attemp
class Add { constructor(...words) { this.words = words; } print(){ let output = []; for(let i =0; i< this.words.length; i++){ output.push("$"+this.words[i]+"$") } console.log(output.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();
Advertisement
Answer
Write output.push('$' + this.words[i])
instead of output.push("$"+this.words[i]+"$")
and at last push $
to the output array.
class Add { constructor(...words) { this.words = words; } print() { let output = []; for (let i = 0; i < this.words.length; i++) { output.push('$' + this.words[i]); } output.push('$'); console.log(output.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();