什么是字符串,或者它是从哪里来的

What is String or where does this come from?

本文关键字:字符串 或者 什么      更新时间:2023-09-26

在试图理解d3时,我看到了.text(String);这行。我不明白弦应该是什么。我想也许它是一个空字符串(不),一个方法(我没有在api参考中看到),并思考它还可以是什么。

我在下面注释了它并得到了预期的结果。我不明白的是什么是字符串,为什么它工作。在这一行中,我的3个方框有文本(它是稍后将表示的数据的内部值),而注释掉它没有。

演示Html

<div class='chart' id='chart-10'/>
<script src="http://d3js.org/d3.v3.min.js"></script>

JS:

    var w = 360;
    var h = 180;
  var svg = d3.select("#chart-10").append("svg")
      .attr("width", w)
      .attr("height", h);
  var g = svg.selectAll(".data")
      .data([50,150,250])
    .enter().append("g")
      .attr("class", "data")
      .attr("transform", function(d, i) { return "translate(" + 20 * (i + 1) + ",20)"; });
  g.append("circle")
      .attr("class", "little")
      .attr("r", 1e-6);
  g.append("rect")
      .attr("x", -10)
      .attr("y", -10)
      .attr("width", 20)
      .attr("height", 20)
      .style("fill", "lightgreen")
      .style("stroke", "green");
  g.append("text")
      .attr("dy", ".35em")
      .attr("text-anchor", "middle")
;//      .text(String);

    g.attr("transform", function(d, i) { return "translate(" + 20 * (i + 1) + ",20)"; });
    g.select("rect").style("opacity", 1);
    g.select("circle").attr("r", 1e-6);
    var t = g.transition().duration(750);
    t.attr("transform", function(d, i) { return "translate(" + d + ",90)"; });
    t.select("circle").attr("r", Math.sqrt);
    t.select("rect").style("opacity", 1e-6);

它看起来像String构造函数。根据d3文档,正如Matt指出的:

如果value是一个函数,则对每个选定元素(按顺序)求值该函数,传递当前数据d和当前索引i,并将此上下文作为当前DOM元素。然后使用函数的返回值设置每个元素的文本内容。

因此,您在几行之前将g.data设置为[50,150,250]。每个数字由String构造函数转换为String对象,返回并用作DOM节点的文本值。

相关文章: