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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16058791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:06:27  来源:igfitidea点击:

d3.js: how to use map function?

javascriptd3.js

提问by Richard

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__; 
});

采纳答案by Lars Kotthoff

You can't -- d3.map()isn't for mapping a function across an array, but a shim for hashes. 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.

你不能——d3.map()不是用于跨数组映射函数,而是用于散列的垫片。简而言之,虽然对象可以像散列一样使用,但在某些情况下可能会发生意外行为。一个新的 Javascript 标准提出了一个解决方案,在它实施之前,d3.map()可以用来达到同样的效果。

More information in the documentation.

文档中的更多信息。

回答by Brittany Alkire

.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. but i also need the output from running nproc in my calculation, and nproc gives me how many cores over which things are distributed. 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 获取的数据为我每 5-15 分钟平均负载提供 0.28、0.03、1.0、0.97、0.04 等数字时,我需要查看以百分比表示的内容。但我还需要在我的计算中运行 nproc 的输出,nproc 为我提供了分布在哪些内核上的数量。所以每次 /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);