Reputation: 197
I'm still on my learning curve in Javascript and trying to complete the last task on SoloLearn. I have to print out the input all together for example the first one "$hello$how$are$you$".
I've tried this so far, by doing a for loop and pushing it into an empty var and then join them together, but no luck so far. Any advice please?
class Add {
constructor(...words) {
var completeWord = "";
this.words = words;
this.print = function(){
for(x=0;x<words.length;x++){
completeWord.push[x];
}
}
completeWord.join("");
console.log(completeWord);
}
//your code goes here
}
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();
Upvotes: 0
Views: 156
Reputation: 370729
Just .join
the array by the separator, and add the separator to both ends of the resulting string:
class Add {
constructor(...words) {
this.words = words;
}
print() {
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();
But JS isn't Java - there's no need for a class just to wrap a single method. If at all possible, use a plain function instead, it has less overhead and will make more structural sense:
const add = (...words) => console.log('$' + words.join('$') + '$');
add("hehe", "hoho", "haha", "hihi", "huhu");
add("this", "is", "awesome");
add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit");
Upvotes: 4