Javascript:如何将引号添加到数组中的各个值?

时间:2017-06-26 18:30:22

标签: javascript arrays csv

我有一个检索和显示csv文件值的函数。

功能

var IDArr = [];
var fileInput = document.getElementById("csv");

readFile = function() {
  console.log("file uploaded")
  var reader = new FileReader();
  reader.onload = function() {
    // document.getElementById('out').innerHTML = reader.result;

    // I assigned the IDs retrieved from the CSV file to an array named keys
    IDArr.push(reader.result);
    // var keys = [reader.result];
    var promises = IDArr.map(function(key) {
      return firebase.database().ref("/Agents/").child(key).once("value");
    });
    // read the data from the database for each ID
    Promise.all(promises).then(function(snapshots) {
      snapshots.forEach(function(snapshot) {
        console.log(snapshot.key + ": " + snapshot.val());
      });
    });
  };

  // start reading the file. When it is done, calls the onload event defined above.
  reader.readAsBinaryString(fileInput.files[0]);
};

if (fileInput) {
  fileInput.addEventListener('change', readFile);
}

以上功能产生下面的图像

enter image description here

我需要在每个ID值周围加​​上引号,并用逗号分隔每个ID值。例如,我想创建一个看起来像这样的新数组" 75799757"," 9744710"," 79989647"," 99029704"我该如何实现呢?

2 个答案:

答案 0 :(得分:1)

let str = "ID 75799757 9744710 79989647 9902970";
let arr = str.split(" ").splice(1);
let result = arr.map((val) => '"'+val+'"').reduce((a,b) => a+','+b);

之后,结果看起来像"75799757","9744710","79989647","99029704"

答案 1 :(得分:0)

var str = ...;
var parts = str.split(" ");
str = "'" + parts[0] + "'";
for (var i = 1; i < parts.length; i++) {
  str += ",'" + parts[i] + "'";
}