gpt4 book ai didi

javascript - 查找数组对象中的中间数字

转载 作者:行者123 更新时间:2023-12-03 11:04:16 25 4
gpt4 key购买 nike

我有一个数组对象:

var checkin_status = [{
"startdate":"2015-01-08",
"totaldays":"4",
"roadmap":[
{ "gifttype": "stars", "quantity": 100, "day": 1},
{ "gifttype": "stars", "quantity": 500, "day": 3},
{ "gifttype": "stars", "quantity": 1000, "day": 10},
{ "gifttype": "stars", "quantity": 1200, "day": 20},
{ "gifttype": "stars", "quantity": 2200, "day": 30},
]
}];

var checkin_info = checkin_status[0].roadmap;
var total = 0;
for (var i = 0; i < checkin_info.length; ++i){
total += checkin_info[i].day;
alert(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

到目前为止,该代码已尝试过,我需要对象添加下一个索引号,例如:day 1+ day 3 = 4 ,那么下一个将是 3 + 10 = 13 等等。我需要的输出类似于 4,13,20,50

知道如何做到这一点吗?

最佳答案

这是 for 循环答案:

var checkin_status = [{
"startdate": "2015-01-08",
"totaldays": "4",
"roadmap": [{
"gifttype": "stars",
"quantity": 100,
"day": 1
}, {
"gifttype": "stars",
"quantity": 500,
"day": 3
}, {
"gifttype": "stars",
"quantity": 1000,
"day": 10
}, {
"gifttype": "stars",
"quantity": 1200,
"day": 20
}, {
"gifttype": "stars",
"quantity": 2200,
"day": 30
}, ]
}];

var checkin_info = checkin_status[0].roadmap;
var output = [];
for (var i = 1; i < checkin_info.length; ++i) {
output.push(checkin_info[i - 1].day + checkin_info[i].day);
}
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

这是 jquery 每个答案:

var checkin_status = [{
"startdate": "2015-01-08",
"totaldays": "4",
"roadmap": [{
"gifttype": "stars",
"quantity": 100,
"day": 1
}, {
"gifttype": "stars",
"quantity": 500,
"day": 3
}, {
"gifttype": "stars",
"quantity": 1000,
"day": 10
}, {
"gifttype": "stars",
"quantity": 1200,
"day": 20
}, {
"gifttype": "stars",
"quantity": 2200,
"day": 30
}, ]
}];
var checkin_info = checkin_status[0].roadmap;
var output = [];
$.each(checkin_status[0].roadmap, function(index, obj) {
if (index === 0)
return;
output.push(checkin_info[index - 1].day + obj.day);
});
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - 查找数组对象中的中间数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27937998/

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