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
JavaScript
x
4
1
$hehe$hoho$haha$hihi$huhu$
2
$this$is$awesome$
3
$lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$
4
The way I tried is wrong, since after each element should be only one string, but the output for my code is
JavaScript
1
5
1
$hehe$$hoho$$haha$$hihi$$huhu$
2
$this$$is$$awesome$
3
$lorem$$ipsum$$dolor$$sit$$amet$$consectetur$$adipiscing$$elit$
4
5
My attemp
JavaScript
1
20
20
1
class Add {
2
constructor(words) {
3
this.words = words;
4
5
}
6
print(){
7
let output = [];
8
for(let i =0; i< this.words.length; i++){
9
output.push("$"+this.words[i]+"$")
10
} console.log(output.join(''))
11
12
}
13
}
14
15
var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");
16
var y = new Add("this", "is", "awesome");
17
var z = new Add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit");
18
x.print();
19
y.print();
20
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.
JavaScript
1
29
29
1
class Add {
2
constructor(words) {
3
this.words = words;
4
}
5
print() {
6
let output = [];
7
for (let i = 0; i < this.words.length; i++) {
8
output.push('$' + this.words[i]);
9
}
10
output.push('$');
11
console.log(output.join(''));
12
}
13
}
14
15
var x = new Add('hehe', 'hoho', 'haha', 'hihi', 'huhu');
16
var y = new Add('this', 'is', 'awesome');
17
var z = new Add(
18
'lorem',
19
'ipsum',
20
'dolor',
21
'sit',
22
'amet',
23
'consectetur',
24
'adipiscing',
25
'elit'
26
);
27
x.print();
28
y.print();
29
z.print();