且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

d3.max()没有返回数组中的最大值?

更新时间:2022-02-11 08:56:40

正如所料, d3.max ()确实返回了最大值...但是,它返回字符串中的最大值,而不是数字中的最大值。

As expected, d3.max() is indeed returning the maximum value... however, it is returning the maximum value among strings, not among numbers.

解释是,默认情况下, d3.csv()会将所有值加载为字符串,即使它们是数字。因此,当你这样做时:

The explanation is that, by default, d3.csv() will load all the values as strings, even if they are numbers. Therefore, when you do:

var value = record[year];

value 是一个字符串,而不是一个数字。在JavaScript中,字符串数组的最大值与数组数组的最大值不同。例如,使用数字:

value is a string, not a number. And in JavaScript the maximum for an array of strings is different from the maximum for an array of numbers. For instance, using numbers:

var myArray = [1, 65, 9, 32, 42];
console.log(d3.max(myArray));

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

这是预期值。但是看看如果我们使用字符串会发生什么:

That's the expected value. But look what happens if we use strings:

var myArray = ["1", "65", "9", "32", "42"];
console.log(d3.max(myArray));

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

解决方案:将您的值更改为数字:

Solution: change your values to numbers:

var value = +record[year];