javascript 获取数组的最后一个值并将其显示在 X 轴下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5856682/
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-25 18:35:07  来源:igfitidea点击:

Getting the last value of an Array and showing it under X axis

javascriptprototypejsflotr

提问by Headshota

var NewdateData[] = [1,2,3,4,5,6,7,8,9,1,2,1,23,45,56]

This NewdateDatais dynamically filled from database depending upon the selection made from the user interface.

NewdateData是根据从用户界面所做的选择从数据库动态填充的。

I am using this NewdateDatafor displaying under the X axis Charts.

我使用它NewdateData在 X 轴图表下显示。

The issue I am facing is that, the values are not taken till the end , I want to have the last value to have under the X axis Labels.

我面临的问题是,直到最后才取值,我想在 X 轴标签下获得最后一个值。

xaxis: {tickFormatter: function(n)
{
    var k = Math.round(n);
    return NewdateData[k]; 
}

I am using flotr.

我正在使用flotr

回答by Headshota

You can get the last value of an array with:

您可以使用以下命令获取数组的最后一个值:

NewdateData[NewdateData.length-1];

回答by Shawn Swanson

I don't have enough points to comment on Radman's post., but his solution is wrong.

我没有足够的分数来评论 Radman 的帖子。但他的解决方案是错误的。

let arr = [1, 2, 3, 4, 5]; let last = arr.slice(-1); // last = 5

让 arr = [1, 2, 3, 4, 5]; 让 last = arr.slice(-1); // 最后= 5

Returns [5], not 5.

返回 [5],而不是 5。

The slice() method returns a shallow copy of a portion of an array into a new arrayobject selected from begin to end (end not included). The original array will not be modified.

slice() 方法将数组的一部分的浅拷贝返回到从开始到结束(不包括结束)选择的新数组对象中。不会修改原始数组。

The correct answer:

正确答案:

let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1)[0];

References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

参考资料:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

回答by radman

Very late to the party, but for posterity: in ES2015/ES6 you can use Array.prototype.slice. Doesn't mutate the array and a negative number gives you elements from the end of the array as a new array.

聚会很晚,但为了后代:在 ES2015/ES6 中,您可以使用Array.prototype.slice。不改变数组,负数将数组末尾的元素作为新数组。

So to get the last element:

所以要获取最后一个元素:

let arr = [1, 2, 3, 4, 5];
let last = arr.slice(-1); // last = 5