D3:对象调用前的 + 运算符

D3: + operator before object call

本文关键字:运算符 调用 对象 D3      更新时间:2023-09-26

我不清楚 + 运算符在这个特定上下文中做什么,或者它在下面的上下文中通常在 javascript 中做什么。投影功能内部。

 function agg_year(leaves) {
            var total = d3.sum(leaves, function(d) {
                return d['attendance'];
            });
            var coords = leaves.map(function(d) {
                return projection([+d.long, +d.lat]);
            });
            var center_x = d3.mean(coords, function(d) {
                return d[0];
            });
            var center_y = d3.mean(coords, function(d) {
                return d[1];
            });
            return {
              'attendance' : total,
              'x' : center_x,
              'y' : center_y
            };
        }

它在 javascript 中将值强制为数字。因此,如果数组中有两个字符串值:

var latitude = '10'; //this is a string
var longitude = '20'; //this is a string

这将创建一个字符串数组,对吧?

var coordinates = [latitude, longitude]; // -> two strings, ['10', '20'];

现在这将创建一个数字数组(+用于将值强制为数字):

var coordinates = [+latitude, +longitude]; // -> two numbers,  [10, 20];

更多例子如下:

var a = null;
typeof a; //object.
typeof +a; //number
+a; //0
var b = '5';
typeof b; //string
typeof +b; //number
+b; //5