javascript - JavaScript。如果 sum == 0,则在数组中查找某个参数的总和以产生弹出窗口
问题描述
$(function () {
$('.performance-container').each(function () {
var container = $(this);
var updateForm = $('.performance-form', container);
var chartCanvas = $('.performance-canvas', container)[0];
var chart = null;
$('.performance-datetimepicker', container).datetimepicker({
widgetPositioning: {
horizontal: "auto",
vertical: "bottom"
}
});
updateForm.submit(function (event) {
window.classiDocs.showLoadingOverlay(container.parents('.x_panel'));
$.post(window.classiDocs.reporting.routes.classificationPerformance, updateForm.serialize(),
function (data) {
var chartData = data.Items.map(function (historyItem) {
return { x: historyItem.Timestamp, y: historyItem.Value };
});
if (!chart) {
initialize(chartData);
} else {
chart.data.datasets[0].data = chartData;
chart.update();
}
})
.always(function () {
window.classiDocs.hideLoadingOverlay(container.parents('.x_panel'));
});
event.preventDefault();
});
$(updateForm).submit();
function initialize(data) {
console.log(data);
chart = new Chart(chartCanvas.getContext("2d"), {
type: "line",
data: {
datasets: [
{
backgroundColor: "rgba(38, 185, 154, 0.31)",
borderColor: "rgba(38, 185, 154, 0.7)",
pointBorderColor: "rgba(38, 185, 154, 0.7)",
pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointBorderWidth: 1,
lineTension: 0,
tension: 0,
data: data
}
]
},
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
title: function (items) {
return new Date(items[0].xLabel).toLocaleString();
},
label: function (item) {
return item.y.toLocaleString();
},
footer: function () {
return null;
}
}
},
scales: {
xAxes: [
{
type: "time",
scaleLabel: {
display: true,
labelString: 'Time Span',
fontSize: 20,
fontColor: "#555555"
}
}
],
yAxes: [
{
scaleLabel: {
display: true,
labelString: 'Number Of Classifications',
fontSize: 20,
fontColor: "#555555"
},
ticks: {
beginAtZero: true
}
}
]
}
}
});
}
});
});
大家好。我对开发还是新手,所以请原谅任何不正确的术语使用。我的目标是在 y 轴上的值之和等于 0 时添加一个弹出窗口。 console.log(data); 在此代码中返回两个对象数组。这些数组中的数据在控制台中返回如下:
0: {x: "2020-10-01T00:00:00", y: 0}
1: {x: "2020-10-01T00:30:00", y: 0}
2: {x: "2020-10-01T01:00:00", y: 0}
3: {x: "2020-10-01T01:30:00", y: 0}
4: {x: "2020-10-01T02:00:00", y: 0}
5: {x: "2020-10-01T02:30:00", y: 0}
这个图表是动态使用的,所以这个脚本会生成两个图表。我如何遍历两个数组并找到每个数组的“y”之和?提前致谢。
解决方案
您可以使用Array.prototype.reduce,这是完整的代码
if (data.reduce((a, v) => a + v.y, 0) === 0) {
alert('The sum of data.y is zero!');
}