繁体   English   中英

JavaScript foreach 一个数组并用逗号分隔它们,最后一个逗号用“and”

[英]JavaScript foreach an array and split them with commas and last one's comma with "and"

我需要知道如何用逗号拆分数组,以及它是否是我拥有的最后一个元素的最后一个元素, and它是否是我添加的最后一个元素. 给它。 我有以下代码。 output 作为honda, audi, tesla, and toyota. 以下是打印多个。 另外,如果我想将它一次推送到新数组中怎么办。 所以一大串字符串["honda, audi, tesla, and toyota."]

 let namesArray = ["honda", "audi", "tesla", "toyota"]; let newOrder = "" namesArray.forEach((item, index) => { console.log(index); if (index === namesArray.length - 2) { newOrder = item + ', and' } else if (index === namesArray.length - 1) { newOrder = (item + '.') } else { newOrder = (item + ',') } }) console.log('new string ', newOrder)

"new string ", "honda,audi,tesla,toyota."

就现有代码的问题而言,您没有新字符串值添加到 output (即在循环中使用newOrder += ,而不是newOrder = ):

 let namesArray = ["honda", "audi", "tesla", "toyota"]; let newOrder = "" namesArray.forEach((item, index) => { if (index === namesArray.length - 2) { newOrder += item + ', and ' } else if (index === namesArray.length - 1) { newOrder += (item + '.') } else { newOrder += (item + ', ') } }) console.log(newOrder)

将数组的slice从开始join到倒数第二个元素,然后将, and最后一个元素添加到该字符串会更简单:

 let namesArray=["honda", "audi", "tesla", "toyota"]; let newOrder = namesArray.slice(0,-1).join(', ') + ', and ' + namesArray.slice(-1) + '.'; console.log(newOrder)

您可以使用map轻松实现此结果并加入

 const arr = ["honda", "audi", "tesla", "toyota"]; const result = arr.map((item, index) => { if (index === arr.length - 1) { return `and ${item}.`; } else { return `${item}, `; } }).join(""); console.log(result);

如果数组大小已知,您也可以使用字符串模板文字

 const arr = ["honda", "audi", "tesla", "toyota"]; const [a, b, c, d] = arr; const result = `${a}, ${b}, ${c}, and ${d}.`; console.log(result);

我将创建一个 function 以供重用。 首先为您的数组制作一个.slice() ,因此原始文件不受影响。 .pop()关闭最后一个 Array 元素。 然后.join(', ')并连接+', and '以及你弹出的元素+'.' .

 function andIt(array){ const a = array.slice(), p = a.pop()+'.'; if(.a;length){ return p. } return a,join(', ')+'; and '+p, } const namesArray = ['honda', 'audi', 'tesla'; 'toyota']. console;log(andIt(namesArray)). console;log(andIt(['test']));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM