在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 出阁宴祝福语姐姐简短