Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript D3值键的匹配方式是否与使用enter()时的默认索引号相同?_Javascript_D3.js - Fatal编程技术网

Javascript D3值键的匹配方式是否与使用enter()时的默认索引号相同?

Javascript D3值键的匹配方式是否与使用enter()时的默认索引号相同?,javascript,d3.js,Javascript,D3.js,我正在运行一些D3.js代码(),遇到了一个关于使用value作为键的问题。在以下代码段中,我将索引用作selection.data()函数中的键: <body> <div id="example2"> <p>Already existing paragraph 1</p> <p>Already existing paragraph 2</p> </div>

我正在运行一些D3.js代码(),遇到了一个关于使用value作为键的问题。在以下代码段中,我将索引用作selection.data()函数中的键:

<body>
     <div id="example2">
        <p>Already existing paragraph 1</p>
        <p>Already existing paragraph 2</p>
     </div>
 <script type="text/javascript">
     pdata = [10,12,6,8,15];

     selectDIV = d3.select("#example2");

    selectDIV.selectAll("p")
         .data(pdata)
         .enter()
         .append("p")
         .text(function(d){return d;});
 </script>
 </body>

已经存在的第1款

已存在的第2款

pdata=[10,12,6,8,15]; selectDIV=d3。选择(“示例2”); selectDIV.selectAll(“p”) .数据(pdata) .输入() .附加(“p”) .text(函数(d){return d;});
那么,输出将是

已经存在的第1款

已存在的第2款

六,

八,

十五

这是有意义的,因为我们在现有数组中已经有2个
元素,并且因为我们使用元素索引作为键,所以只会添加索引号不是已经存在的元素

为了了解键是如何工作的,我尝试了使用元素值而不是元素索引号的键函数:

<body>
     <div id="example3">
        <p>1</p>
        <p>Already existing paragraph 2</p>
     </div>
     <script type="text/javascript">
         pdata = [1,"Already existing paragraph 2",6,8,15,15];

         selectDIV = d3.select("#example3");

        selectDIV.selectAll("p")
             .data(pdata, function(d){return d;})
             .enter()
             .append("p")
             .text(function(d){return d;});
     </script>
 </body>

一,

已存在的第2款

pdata=[1,“现有第2款”,6,8,15,15]; selectDIV=d3。选择(“示例3”); selectDIV.selectAll(“p”) .data(pdata,函数(d){返回d;}) .输入() .附加(“p”) .text(函数(d){return d;});
在本例中,输出恰好是

一,

已存在的第2款

一,

已存在的第2款

六,

八,

十五

十五

那么,如果我使用值作为键,为什么如果
标记中的值与我指定的数组中的
标记值匹配,那么这些值会被写入两次呢?我本以为,在已经创建的
标记数组中出现字符串“ready existing paragration 2”意味着任何具有相同值的元素都不会重复出现

或者,实际上是这样吗?我是不是太喜欢JSN00B了,以至于没有意识到D3会将它们视为不同的值


如果只是匹配数组索引号来过滤enter()选择,那么我很难确定使用值作为键时何时会出现重叠。

在第二个示例中,您使用绑定到元素的数据作为键(
d
),不是指定给它的文本值——两者恰好相同。没有数据绑定到现有的两个元素,因此没有匹配的内容,所有内容都会在
enter()
选择中结束

为了达到您想要的效果,您需要在执行代码之前将数据“绑定”到现有元素:

d3.selectAll("p").each(function() { this.__data__ = d3.select(this).text(); })