连接JavaScript数组时的额外逗号

时间:2016-09-12 23:47:53

标签: javascript jquery

我正在尝试将一些JavaScript数组写入CSV文件。但是,我需要在某些位置添加换行符。以下代码有效,但它意外地将,添加为第2行中的第一个元素(或者说它从第2行开始添加,)。我想知道是什么造成的?提前谢谢!

当前输出

Chemical, CAS, MW
, water, 00566, 666

欲望输出

Chemical, CAS, MW
water, 00566, 666

var Chem1 = "water"
var CAS1 = "00566"
var MW1 = "666"

var csv_content = []
var csv_content_final = []
csv_content[0] = ["Chemical, CAS, MW"];
var chem_property = [Chem1, CAS1, MW1];
csv_content[1] = chem_property;
for (kkk = 0; kkk < ($(csv_content).size()); kkk++) {
      csv_content_final[kkk] = csv_content[kkk] + '\n';
}

alert(csv_content_final)

JSFIDDLE

2 个答案:

答案 0 :(得分:2)

,的原因是因为根据定义,CSV格式为' C omma S eparated V alues'< / p>

新行不被视为分隔符,只能是逗号。

编辑:

如果你真的想在开始时没有逗号,这将有效: console.log(csv_content_final.join(''));

http://fiddle.jshell.net/L8zdqo4u/

但这是 CSV

enter image description here

答案 1 :(得分:1)

我不确定你为什么得到var Chem1 = "water" var CAS1 = "00566" var MW1 = "666" var csv_content = [] var csv_content_final = [] csv_content[0] = ["Chemical, CAS, MW"]; var chem_property = [Chem1, CAS1, MW1]; csv_content[1] = chem_property; console.log(csv_content.join('\n')); 但是如果你删除for循环,并依赖于使用逗号的数组的默认连接,那么你只需加入csv_content数组(&#39; \ n&#39;)如下......

<script>
var data ="";
var first = "";
var sum = "";
document.write('<button onclick="one()">1</button>');
document.write('<button onclick="two()">2</button><br/>');
document.write('<button onclick="three()">3</button>');
document.write('<button onclick="four()">4</button><br/>');
document.write('<button onclick="five()">5</button>');
document.write('<button onclick="six()">6</button><br/>');
document.write('<button onclick="seven()">7</button>');
document.write('<button onclick="eight()">8</button><br/>');
document.write('<button onclick="nine()">9</button>');
document.write('<button onclick="zero()">0</button><br/>');
document.write('<button onclick="add()">+</button>');
document.write('<button onclick="equal()">=</button><br/>');
document.write('<div id =\"sum\"> </div><br/>');
function one(){
data = data + "1";
}
function two(){
data = data + "2";
}
function three(){
data = data + "3";
}
function four(){
data = data + "4";
}
function five(){
data = data + "5";
}
function six(){
data = data + "6";
}
function seven(){
data = data + "7";
}
function eight(){
data = data + "8";
}
function nine(){
data = data + "9";
}
function zero(){
data = data + "0";
}
function add(){
 first = data;
 data= "";
}

function equal(){
 sum = parseInt(first) + parseInt(data);



 //document.getElementById("sum").remove();
 document.getElementById("sum").innerHTML =   sum  ;

      data ="";
  first = "";
 sum = "";
}




</script>