我有一个数组返回一些数字,如222.000,333.000,444.000,555.000。理想情况下,我想格式化,因此它设置了一个分界线" \ n"在每隔一个号码之后。即会像
222.000,333.000
444.000,555.000
可以通过修改下面的行来完成吗?
n107 = parseFloat(output1),
n108 = parseFloat(output2),
n109 = parseFloat(output3),
n110 = parseFloat(output4),
list = [];
// add values to array if they're not NaN or > 0
if (n1) {
list.push(n1);
}
if (n2) {
list.push(n2);
}
if (n3) {
list.push(n3);
}
if (n4) {
list.push(n4);
}
if (n5) {
list.push(n5);
}
if (n6) {
list.push(n6);
}
// combine values into a string separated with commas
document.getElementById('inputTextToSave').innerHTML = list.join(",");
答案 0 :(得分:1)
这不是最佳解决方案。但它有效
n107 = parseFloat("222.00"),
n108 = parseFloat("333.00"),
n109 = parseFloat("444.000"),
n110 = parseFloat("55.00"),
list = [n107,n108,n109,n110];
// combine values into a string separated with commas
//document.getElementById('inputTextToSave').innerHTML = list.join("</br>");
var j =1;
var htmlString = '';
for(var i =0; i< list.length; i++){
if(j<2){
htmlString += list[i]+",";
j++;
}else{
htmlString += list[i]+"</br>";
j=1;
}
}
document.getElementById('inputTextToSave').innerHTML = htmlString;
<div id="inputTextToSave"></div>
答案 1 :(得分:0)
您需要在循环中创建自己的字符串,而不是使用join()
。
有很多方法可以创建循环...关键是检查循环中的索引以确定使用哪个分隔符
var list = [222.000,333.000,444.000,555.000];
var res = list.reduce((newStr, currVal, index) =>
newStr += (index % 2 ===1 ? ',' :'\n') + currVal );
document.getElementById('inputTextToSave').innerHTML = res;
<pre id="inputTextToSave"></pre>
答案 2 :(得分:0)
可以使用Array.reduce方法完成。
const list = ['222.000', '333.000', '444.000', '555.000']
const result = list.reduce((memo, item, index) => {
const comma = (index+1)%2 === 0 ? ',' : ''
const lineBreak = (index+1)%2 === 0 ? '<br />' : ''
memo += comma + item + lineBreak
return memo
}, '')
document.getElementById('inputTextToSave').innerHTML = result;
&#13;
<div id="inputTextToSave"></div>
&#13;
答案 3 :(得分:-1)
另一种选择:
document.getElementById('inputTextToSave').innerHTML =
list.join(',').replace(/([^,]+,[^,]+),/g, '$1<br>')