簡體   English   中英

我在處理排序函數的 JS 代碼中收到錯誤

[英]I am receiving an error from my JS code dealing with a sort function

所以我有這個用於類的代碼,但是每當我運行它時,瀏覽器中都沒有顯示任何內容,而是在控制台下,我收到一個錯誤,指出 data.sort 不是一個函數。

這是完整的代碼。

// Use d3 to read the JSON file.
// The data from the JSON file is arbitrarily named importedData as the argument.
d3.json("data/data.json").then((importedData) => {
  // console.log(importedData);
  var data = importedData;

  // Sort the data array by using the greekSearchResults value.
  data.sort(function(a, b) {
    return parseFloat(b.greekSearchResults) - parseFloat(a.greekSearchResults);
  });

  // Slice the first 10 objects for plotting.
  data = data.slice(0, 10);

  // Reverse the array because of the Plotly defaults.
  data = data.reverse();

  // Trace1 for the Greek data.
  var trace1 = {
    x: data.map(row => row.greekSearchResults),
    y: data.map(row => row.greekName),
    text: data.map(row => row.greekName),
    name: "Greek",
    type: "bar",
    orientation: "h"
  };

  // Data
  var chartData = [trace1];

  // Apply the group bar mode to the layout.
  var layout = {
    title: "Greek gods search results",
    margin: {
      l: 100,
      r: 100,
      t: 100,
      b: 100
    }
  };

  // Render the plot to the div tag with the id of "plot".
  Plotly.newPlot("plot", chartData, layout);
});

sort是一種數組方法。 我的猜測是 importData 變量不是數組,因此您會收到該錯誤。 如果您想使用它,請確保從數據響應創建一個數組。

sort - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM