它应该采用多个单词并输出组合版本,其中每个单词由美元符号 $ 分隔。
例如,对于单词“hello”、“how”、“are”、“you”,输出应为“$hello$how$are$you$”。
class Add {
constructor(...words) {
this.words = words;
}
all(){console.log('$'+ this.words)};
}
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.all();
输出
$hehe,hoho,haha,hihi,huhu
预期产出
$hehe$hoho$haha$hihi$huhu$
$this$is$awesome$
$lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$
现在您正在将数组的 toString 连接到美元符号。这将添加一个逗号分隔的字符串。
Array.join
class Add {
constructor(...words) {
this.words = words;
}
all() {
const output = this.words?.length ? `$${this.words.join("$")}$` : "No input";
console.log(output)
};
}
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");
var nope = new Add()
x.all();
y.all();
z.all();
nope.all();
您似乎对数组的概念有疑问(您的变量
this.words
是一个数组)。在做其他事情之前,您可能想先研究一下数组和迭代。
这里有一些可能有帮助的链接:
基本上,如果您想对数组的值执行某些操作,您应该学习使用 for 循环来执行此操作,这是一种遍历(迭代)数组中包含的每个值并执行特定操作的方法这些价值观。
我知道实际上有很多方法可以做到这一点(使用 join 是其中之一),但我建议您首先尝试了解基础知识。
带有 for 循环的代码示例如下所示:
class Add {
constructor(...words) {
this.words = words;
}
all() {
let newString = "";
for (let word of this.words) {
newString += "$" + word;
}
console.log(newString + "$");
}
}
var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");
x.all();