首页 > 解决方案 > 如何修复javascript中的“ids is not a function”错误

问题描述

我的最终目标是使用 chartist.js 中的数组数据来创建仪表板。我是 javascript 和编程的初学者,我知道我需要为图表添加变量。我的第一个目标是在继续之前添加更多的 console.log 以查看阵列。

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" type="text/css" />
  <meta charset="utf-8">
  <title>first chart</title>
</head>
<body>
<div id="chart" class="ct-golden-section"></div> 
<script>

fetch('https://script.google.com/macros/s/AKfycbxY1tXSC6zbwvRc330EfyBNKgE0YiLWXx6p868uJh2d/dev')

    .then(function(response) {
        return response.json();
    })
    //.then(data => console.log(data))
//declare the data variable   
    var data = {
      //set our labels (x-axis) to the Label values from the JSON data
      labels: ids.map(function(id) {
        return id.Date;
      }),
      //set our values to Value value from the JSON data
      series: ids.map(function(id) {
        return id.Weight;
      })
    };

</script>

</body>
</body>
</html>
</body>
</html>

标签: javascriptchartist.js

解决方案


查看发回的 JSON 数据后,我发现您试图错误地访问数据(使用地图)。相反,您想直接访问其结构内的每个数组(存在:重量 > 日期,重量 > 重量)。有时您需要分析您收到的对象以检索正确的数据

其次,查看您在评论中发布的链接后,您似乎错过了关键代码.then(function(ids))。完整功能如下图所示:

fetch('https://script.google.com/macros/s/AKfycbxY1tXSC6zbwvRc330EfyBNKgE0YiLWXx6p868uJh2d/dev')

    .then(function(response) {
        return response.json();
    })
    .then(function(ids) {  //Code that is required
        var data = {
            //set our labels (x-axis) to the Label values from the JSON data
            labels: ids.weight.Date,        //Retrieve relevant array
            //set our values to Value value from the JSON data
            series: ids.weight.Weight       //Retrieve relevant array
    }
  });

当它调用时.then(function(ids)),它正在等待前一个语句执行,然后将前一个调用的返回值作为变量 ids 传递。在您的代码中,从未定义过 ids 。


推荐阅读