【问题标题】:How to Array to string in javascript?如何在javascript中将字符串排列成字符串?
【发布时间】:2020-04-02 16:48:30
【问题描述】:

我正在尝试让字符串方法与数组一起使用,但我一直得到一个空字符串

let url = "https://api.myjson.com/bins/be7fc"

    let data =[];
    fetch(url)
        .then(response => response.json())
        .then(result => data.push(result[0].id));
//Array
    console.log(data); 
// to string
    let x = data.toString();
    console.log(x);

Image of console

我不确定我错过了什么

【问题讨论】:

  • 问题是您的数组在您log 时为空,但在您单击展开时已填充。我确定有一个解释很好的副本,但我仍在寻找它。
  • This Q&A 解释了 Chrome 控制台的扩展行为,但并没有真正涉及您更普遍的异步问题(即,如果您使用的是then) 中产生的值

标签: javascript arrays json string


【解决方案1】:

使用 join 而不是 toString() 并且你应该在获取成功模式下进行。因为在异步部分,你的控制台在你从 api 获取数据之前首先出现。

let url = "https://api.myjson.com/bins/be7fc"

    let data =[];
    fetch(url)
        .then(response => response.json())
        .then(result => {data.push(result[0].id);console.log(data.join(","))});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 2022-01-21
    • 2014-11-29
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多