将Javascript对象转换为数字数组

时间:2016-09-13 07:13:27

标签: javascript d3.js

我有一个有一组数字的对象

> var size = d3.values(data[0]);

>size
output:
["0", "14.71", "50.0", "35.29"]

>typeof(size);
output:
"object"

我想总结宽度并获得如下输出:

  

[0,14.71,64.71,100]

但我得到的输出如下:

>var width = [size[0],
                    size[0]+size[1],
                    size[0]+size[1]+size[2],
                    size[0]+size[1]+size[2]+size[3]];

>width
output:
["0", "014.71", "014.7150.0", "014.7150.035.29"]

请帮我解决这个问题。提前谢谢......

1 个答案:

答案 0 :(得分:10)

您可以使用Array#map和thisArgs以及隐式转换来为元素编号。



var data = ["0", "14.71", "50.0", "35.29"],
    width = data.map(function (a) {
        return this.count += +a;
    }, { count: 0});

console.log(width);




不使用thisArg的ES6(this不适用于arrow function),但关闭count



var data = ["0", "14.71", "50.0", "35.29"],
    width = data.map((count => a => count += +a)(0));

console.log(width);