拆分字符串,然后将其添加到另一个变量中,并包括未定义的内容

时间:2018-11-01 16:29:35

标签: javascript

我有一个字符串,该字符串使用&用作分隔符,我需要将该字符串分割,分割,然后将其添加到带有换行符的另一个变量中。没问题。

问题是,当我将每个拆分字符串添加到另一个变量时,我的字符串中添加了未定义的关键字。

let sentence = "Hi there & How are you & today?";
let sentenceSplit = sentence.split('& ');
let comp;

for(i=0;i<sentenceSplit.length; i++){
comp = sentenceSplit[i] + comp + "\n";

}
console.log(comp);

这就是它的样子

undefinedHi there 
How are you 
today?

应该是

Hi there 
How are you 
today?

如何阻止未定义的关键字出现在新字符串中?

2 个答案:

答案 0 :(得分:1)

您应该将comp变量初始化为空字符串(''),然后才能将其连接起来。

您似乎也要按顺序连接,应该是:

comp = comp + sentenceSplit[i] + '\n';

或更简单地

comp += sentenceSplit[i] + '\n';

制作最终代码:

let sentence = "Hi there & How are you & today?";
let sentenceSplit = sentence.split('& ');
let comp = '';

for (let i = 0; i < sentenceSplit.length; i++){
    comp += sentenceSplit[i] + "\n";
}
console.log(comp);

答案 1 :(得分:1)

您需要初始化comp变量。因为在尝试将comp变量添加到sting数组的第0个元素时未定义。

Set comp = "" 

运行循环之前。