我有一个数组对象:
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
,然后是{{1 }} + 3
= 10
等等。我需要的输出就像13
。
知道怎么做吗?
答案 0 :(得分:1)
这是循环答案:
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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
以下是每个答案的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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
试试这个:
array = checkin_status[0].roadmap.map(function(d){return d.day})
a=0; b=[];
array.forEach(function(d){
if(a != 0){
b.push(a+d)};
a = d
}
)
console.log(b)
答案 2 :(得分:0)
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 = 1; i < checkin_info.length; ++i){
total = checkin_info[i-1].day + checkin_info[i].day;
if (typeof total !== 'undefined'){
console.log(total);
}
}