如何循环在数组和打印所有在JS没有空间在一起?



我仍然在学习Javascript,并试图完成solollearn上的最后一个任务。我必须把所有的输入都打印出来,比如第一个"$hello$how$are$you$"

到目前为止,我已经尝试过了,通过做一个for循环并将其推入一个空变量,然后将它们连接在一起,但到目前为止还没有运气。有什么建议吗?

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();

通过分隔符对数组进行.join,并在结果字符串的两端添加分隔符:

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();

但是JS不是Java——没有必要用一个类来包装一个方法。如果可能的话,使用普通函数代替,它的开销更小,并且更有结构意义:

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");

最新更新