您如何编写一个从数组返回值的函数? [英] How do your write a function that returns values from an array?

查看:73
本文介绍了您如何编写一个从数组返回值的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个数组:

var lineData = [ { "x": 25,   "y": 75},  { "x": 85,   "y": 130},
             { "x": 140,  "y": 190}, { "x": 195,  "y": 245},
             { "x": 195,  "y": 300}, { "x": 25,  "y": 350},
             { "x": 80,  "y": 405}, { "x": 195,  "y": 460}];

现在,我想在数组的坐标上绘制椭圆.如何创建将访问x和y值的函数?函数如何工作?

Now I want to draw ellipses on the coordinates in the array. How do I create a function that will access the x and y values? How do functions work?

// Draw ellipses 
var circle = svgContainer.append("ellipse")
    .attr("cx", function(d) { return d.x; }})
    .attr("cy", function(d) { return d.y; })
    .attr("rx", 5)
    .attr("ry", 5);

推荐答案

使用循环访问数据(如接受的答案)在D3代码中是一个可怕的想法:不仅完全没有必要,而且还违背了D3数据联接的概念,这会使以后的事情变得尴尬(如果您尝试操纵/更改该选择).如果要通过循环解决此问题,为什么首先要使用D3?您接受的解决方案完全是非惯用语.

Using a loop to access the data (as in the accepted answer) in a D3 code is a terrible idea: not only this is completely unnecessary, but it goes against the very concept of D3 data join, and it will make things awkward later on (if you try to manipulate/change that selection). If you will fix this with a loop, why are you using D3 in the first place? The solution you accepted is completely non-idiomatic.

不需要.只需绑定数据并使用输入"选择,即可使用匿名函数的第一个参数访问每个圆的数据:这是D3中著名的function(d).当您这样做时...

You don't need a loop. Simply bind the data and use an "enter" selection, accessing the datum for each circle with the first parameter of the anonymous function: that's the famous function(d) in D3. When you do this...

.attr("cx", function(d){ return d.x})
//first parameter ---^

...每个元素的原点将传递给attr函数.如果您想知道,第二个参数是索引,第三个参数是当前组.另外,参数的实际名称并不重要,仅取决于其顺序.

... the datum for each element will be passed to the attr function. In case you want to know, the second parameter is the index and the third parameter is the current group. Also, the actual name of the parameter doesn't matter, only its order.

以下是使用您的数据的示例:

Here is an example using your data:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 600)
  .attr("height", 500);
  
var lineData = [ { "x": 25,   "y": 75},  { "x": 85,   "y": 130},
  { "x": 140,  "y": 190}, { "x": 195,  "y": 245},
  { "x": 195,  "y": 300}, { "x": 25,  "y": 350},
  { "x": 80,  "y": 405}, { "x": 195,  "y": 460}];
             
var ellipses = svg.selectAll("faraday")
  .data(lineData)
  .enter()
  .append("ellipse")
  .attr("cx", function(d){ return d.x})
  .attr("cy", function(d){ return d.y})
  .attr("rx", 5)
  .attr("ry", 5)
  .attr("fill", "teal");

<script src="https://d3js.org/d3.v4.min.js"></script>

这篇关于您如何编写一个从数组返回值的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆