gpt4 book ai didi

JavaScript:数组迭代缺失值时缺少逻辑

转载 作者:行者123 更新时间:2023-11-30 16:41:35 25 4
gpt4 key购买 nike

当特定月份没有可用数据时,我试图填充空白值。这是 plunker.. http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview

$scope.year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];

var total = ["jan", "feb", "mar", "apr", "may", "jun", "aug", "sep", "oct", "nov", "dec"];


for(var i=0; i<total.length; i++){

if($scope.year[i].month === undefined){ //logic here to see absent month.

$scope.year.push(
{
"month":total[i],
"val":"0"
})
}
}

我已经创建了默认总月项目数组,用于比较预期对象中的每个月项目,如果预期对象中不存在该项目,则需要在预期对象本身中创建空项目或值为“0”。

最佳答案

你可以做如下的事情

Js 更新

var year = [
{"month":"mar", "val":"23"},
{"month":"feb", "val":"45"},
{"month":"jan", "val":"56"}
];

var total = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];


// Current months array
var currentMonth = [];
angular.forEach(year, function(item){
currentMonth.push(item.month);
});

// iterating over months
for(var i=0; i<total.length; i++){
//$scope.year = [];

// checking if month is absent
if(currentMonth.indexOf(total[i]) === -1){ //logic here to see absent month.

year.push(
{
"month":total[i],
"val":"0",
"order" : i
})
} else {
year[currentMonth.indexOf(total[i])].order = i; // adding order
}
}

$scope.year = year;

标记

 <!-- Order by new property order -->
<td ng-repeat="item in year | orderBy: 'order'">
{{item.val}}
</td>

供引用 - http://plnkr.co/edit/km6jLQv8wxm1XP8QCxvV?p=preview

关于JavaScript:数组迭代缺失值时缺少逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com