简体   繁体   English

d3.js:如何使用地图功能?

[英]d3.js: how to use map function?

How can I use d3.map() to get [10, 12] out of the following array? 如何使用d3.map()从以下数组中获取[10, 12]

var mydata = [ 
  { '__data__' : 10 }, 
  {'__data__' : 12 }
]; 

I have been trying this, but it doesn't work: 我一直在尝试这个,但它不起作用:

var mymap = d3.map(mydata, function(d) { 
  return d.__data__; 
});

You can't -- d3.map() isn't for mapping a function across an array, but a shim for hashes. 你不能d3.map()不是用于在数组中映射函数,而是用于散列的垫片。 Briefly, while objects can be used like hashes, there are situations when unexpected behaviour can occur. 简而言之,虽然可以像散列一样使用对象,但是有些情况可能会发生意外行为。 A new Javascript standard proposes a solution to this, and until it is implemented, d3.map() can be used to the same effect. 一个新的Javascript标准提出了一个解决方案,直到它实现, d3.map()可以用于相同的效果。

More information in the documentation . 文档中的更多信息。

.map() just creates another array, having traversed whatever you gave it and performing a function you defined on each element in the old array and then that becomes the new array. .map()只创建另一个数组,遍历你给它的任何数据并执行你在旧数组中的每个元素上定义的函数,然后它就成了新的数组。

so if i wanted to perform a single operation on all elements in an array and make a new array out of it, i'd use .map() 所以如果我想对数组中的所有元素执行单个操作并从中创建一个新数组,我会使用.map()

for example, i need to see something represented as percentages when the data i'm getting from /proc/loadavg gives me numbers like 0.28, 0.03, 1.0, 0.97, 0.04, etc for every 5-15 min load avg. 例如,当我从/ proc / loadavg获得的数据为每5-15分钟的负载平均值给出0.28,0.03,1.0,0.97,0.04等数字时,我需要看到表示为百分比的东西。 but i also need the output from running nproc in my calculation, and nproc gives me how many cores over which things are distributed. 但我还需要在计算中运行nproc的输出,nproc给出了分配内容的核心数。 so i create an array each time /proc/loadavg gives me a new value, and i push each new value onto an array... 所以我每次创建一个数组/ proc / loadavg给我一个新的值,并将每个新值推送到一个数组...

This would be your initial data: 这将是您的初始数据:

var data = [0.28,0.03,1.0,0.97,0.04];
var dataSize = 5;

This could be the function to use to apply to all indexes in your original data array: 这可以是用于应用于原始数据数组中所有索引的函数:

   percent = function () {
      return (loadval/(numCores*100));
   }

This would be mapping it to a new array with the transformed values: 这将使用转换后的值将其映射到新数组:

 data = d3.range(dataSize).map(percent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM