简体   繁体   English

为什么我的JavaScript对象通过返回转换为字符串?

[英]Why does my JavaScript object get converted to a string by returning it?

I'm trying to load some csv data into a JS object. 我正在尝试将一些csv数据加载到JS对象中。 It loads the data converts it to an object and everything is fine within my converting function, but when I try to access it outside the function it appears to be a string and is no longer a JS object. 它加载数据将其转换为对象,并且在我的转换函数中一切正常,但是当我尝试在函数外部访问它时,它似乎是一个字符串而不再是JS对象。

async function loadData() {
    let data = $.get("./p1.csv", function(csv){
        var lines = csv.split("\n");
        var result = [];
        var headers = lines[0].split(",");

        for(var i=1; i<lines.length; i++){
            var obj = {};
            var currentline = lines[i].split(",");

            for(var j=0; j<headers.length; j++){
                obj[headers[j]] = currentline[j];
            }

            result.push(obj);
        }
        console.log("1", result)
        return result; 
    });
    console.log("2", await data)
    return await data;
}

I expect the two print statements to return the same content but they don't. 我希望两个print语句返回相同的内容,但它们不会。 Chrome dev tools output Chrome开发工具输出

SOLVED 解决了

Changing the function to the following solves it: 将功能更改为以下解决方案:

async function loadData() {
    let data = $.get("./p1.csv").then(function(csv){
        var lines = csv.split("\n");
        var result = [];
        var headers = lines[0].split(",");

        for(var i=1; i<lines.length; i++){
            var obj = {};
            var currentline = lines[i].split(",");

            for(var j=0; j<headers.length; j++){
                obj[headers[j]] = currentline[j];
            }

            result.push(obj);
        }
        console.log("1", result)
        return result; 
    });
    console.log("2", await data)
    return await data;
}

You're trying to return from a callback which does not work in JavaScript . 你试图从一个在JavaScript不起作用的回调返回。 Use async/await all the way through: 一直使用async/await

This statement return await data in your code is equivalent to 此语句return await data您的代码中的return await data相当于

let data = $.get("./p1.csv")
return await data; // <-- this returns your raw csv data as string
async function loadData() {
  let csv = await $.get("./p1.csv");
  var lines = csv.split("\n");
  var result = [];
  var headers = lines[0].split(",");

  for(var i=1; i<lines.length; i++){
    var obj = {};
    var currentline = lines[i].split(",");

    for(var j=0; j<headers.length; j++){
      obj[headers[j]] = currentline[j];
    }

    result.push(obj);
  }
  console.log("1", result)
  return result; 
}

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

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