且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型参数不能分配给字符串

更新时间:2022-11-30 11:57:57

您不能将嵌套数组传递给ordinal.domain():序数标度需要具有 plain 数组作为域...更为重要的是,一个数组,即基元,例如字符串(如果您传递数字,它们将仍然被字符串化...).这就解释了您的错误:类型参数无法分配给 string " .

You cannot pass a nested array to ordinal.domain(): an ordinal scale needs to have a plain array as the domain... even more important, an array of values, i.e., primitives, like strings (if you pass numbers they will be stringified anyway...). That explains your error: "Argument of type is not assignable to string".

话虽如此,您可以使用root.descendants()获取所有子项,并使用map获得其所需的属性.在您的情况下,我将假定所需的字符串是子代的name属性.

That being said, you can use root.descendants() to get all the children and map to get their desired properties. In your case, I'll assume that the string you want is the children's name property.

在此演示中,myNames是要传递给有序刻度的数组(如果您不希望根名称,请将其删除):

In this demo, myNames is the array you'll pass to the ordinal scale (if you don't want the root's name, remove it):

const data = {
  "name": "program",
  "children": [{
    "name": "file1",
    "children": [{
      "name": "function1",
      "calls": [{
          "line": 105,
          "file": "file2",
          "function": "function5"
        },
        {
          "line": 106,
          "file": "file2",
          "function": "function6"
        }
      ],
      "lines1": [
        102,
        105
      ],
      "lines2": [
        [
          102,
          102
        ],
        [
          105,
          106,
          107
        ],
        [
          106,
          107
        ]
      ],
      "group": 1
    }],
    "group": 1
  }],
  "group": 0
};

const root = d3.hierarchy(data);

const myNames = root.descendants().map(d => d.data.name);

console.log(myNames)

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>