【问题标题】:Javascript: How can quotation mark be added to individual values in an array?Javascript:如何将引号添加到数组中的单个值?
【发布时间】:2017-06-26 18:30:21
【问题描述】:

我有一个函数可以检索和显示 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);
}

上面的函数产生下面的图像

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

【问题讨论】:

  • 先按空格分割,然后将第一个值移出,最后迭代数组,将数字转换为字符串。
  • 你确定你不只是希望你的数组中的值是字符串。我看不出在数组元素中添加引号和逗号有什么用。
  • @James 我想使用该格式循环遍历 firebase 数据库,但如何将其转换为字符串?
  • 使用Number.toString方法。

标签: javascript arrays csv


【解决方案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"

【讨论】:

  • 当前格式的ID不带引号,在arr中不带引号
  • 最终结果字符串包含一个带双引号的字符串。
【解决方案2】:
var str = ...;
var parts = str.split(" ");
str = "'" + parts[0] + "'";
for (var i = 1; i < parts.length; i++) {
  str += ",'" + parts[i] + "'";
}

【讨论】:

  • 它不分隔 ID 这是它产生的 'ID 75799757 9744710 79989647 99029704'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2021-10-17
  • 1970-01-01
  • 2019-04-30
  • 2013-11-24
  • 1970-01-01
  • 2017-11-23
相关资源
最近更新 更多