在JavaScript中联接数组以形成字符串
我们需要编写一个包含字符串数组的JavaScript函数。该函数应连接数组的所有字符串,将所有空格替换为破折号“-”,然后返回由此形成的字符串。
例如,如果数组为-
const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
那么输出应该是-
const output = "QA-testing-promotion-Twitter-Facebook-Test";
因此,让我们为该函数编写代码-
示例
为此的代码将是-
const arr = ["QA testing promotion ", " Twitter ", "Facebook ", "Test"];
const joinArr = arr => {
const arrStr = arr.join('');
let res = '';
for(let i = 0; i < arrStr.length; i++){
if(arrStr[i] === ' '){
if(arrStr[i-1] && arrStr[i-1] !== ' '){
res += '-';
};
continue;
}else{
res += arrStr[i];
};
};
return res;
};
console.log(joinArr(arr));输出结果
控制台中的输出将为-
QA-testing-promotion-Twitter-Facebook-Test
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短