我需要一个制作文本编码器,但我有一个问题



它应该接受多个单词并输出一个组合版本,其中每个单词用美元符号$分隔。

例如,对于单词"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是一个数组)。在做其他事情之前,您可能希望先查看一下数组和迭代。

这里有几个链接可能会有所帮助:

MDN数组
MDN循环和迭代

基本上,如果你想对数组的值做一些事情,你应该学会用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();

最新更新