如何删除for循环中的最后一个逗号? [英] How can I remove the last comma in my for loop?
本文介绍了如何删除for循环中的最后一个逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function currentLine(katzDeliLine) {
if (katzDeliLine.length > 0) {
var textToPrint = "The line is currently: "
for (var crrLine = 0; crrLine < katzDeliLine.length; crrLine++) {
textToPrint = textToPrint + (crrLine + 1) + ". " + katzDeliLine[crrLine] + ","
}
return textToPrint;
} else {
return "The line is empty"
}
}
var lineofpeople = ["katrina", "kevin", "vincent"]
输出为:
The line is currently: 1. katrina, 2. kevin, 3. vincent,
我正试图摆脱'vincent'之后的最后一个逗号
I'm trying to get rid of the last comma after 'vincent'
我尝试了一个if语句,并且还尝试了.join()方法.我不知道如何在代码中实现它们.
I tried an if statement, and I also tried the .join() method. I don't know how to implement them in the code.
推荐答案
您可以将前导数字与值映射,并用逗号将数组连接起来.
You could map the leading numbers with the value and join the array with comma.
function currentLine(array) {
return array.length
? `The line is currently: ${array.map((v, i) => `${i + 1}. ${v}`).join(', ')}.`
: "The line is empty.";
}
var lineofpeople = ["katrina", "kevin", "vincent"];
console.log(currentLine(lineofpeople));
console.log(currentLine([]));
这篇关于如何删除for循环中的最后一个逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文