我从API获得以下结果
data: {
"total_slots": int,
"occupied_count": int,
"occupied_slots" : [int] e.g.[452,453,459] (here each int in the array signfies an occupied slot),
"slots_down" : [int] e.g.[460,462] (here each int in the array signfies a down slot)
}
我想要以下条件
VAR OCCUPIED, length of the list which are occupied minus length of common slots in occupied and slots_down
VAR TOTAL_SLOTS = total slots (which are 31 i think) - slots which are down
VAR AVAILABLE = (31 - length(slots_down)) - length( slots occupied AND not down)
固定的31个插槽。
var ALL_SLOTS = [452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523];
如何满足VAR AVAILABLE = (31 - length(slots_down)) - length( slots occupied AND not down)
这是我的当前代码
s = JSON.parse(s);
console.log(s);
SLOTS_DOWN = s.slots_down;
var total_slots = s.total_slots;
SLOTS_DOWN = s.slots_down.length;
console.log('down slots are ' + SLOTS_DOWN);
total_slots = parseInt(total_slots) - parseInt(SLOTS_DOWN);
var occupied = s.occupied_count;
var available = parseInt(total_slots) - parseInt(occupied) - parseInt(SLOTS_DOWN);
答案 0 :(得分:2)
根据这些:
你可以试试这个:VAR OCCUPIED,被占用的列表长度减去常见长度 占用的插槽和slots_down VAR TOTAL_SLOTS =总插槽(我认为是31) - 插槽已关闭 VAR AVAILABLE =(31 - length(slots_down)) - 长度(插槽占用而非下降)
var OCCUPIED = data.occupied_count -
data.occupied_slots.filter(function(elem){
return data.slots_down.indexOf(elem)>-1;
}).length;
var TOTAL_SLOTS = data.total_slots.length - data.slots_down.length;
var AVAILABLE = ((data.total_slots.length - data.slots_down.length)) -
data.occupied_slots.filter(function(elem){
return data.slots_down.indexOf(elem)==-1;
}).length
答案 1 :(得分:1)
这应该有效:
data = {
"total_slots": 124,
"occupied_count": 3,
"occupied_slots" : [245, 326, 256],
"slots_down" : [245, 136]
}
var down_but_not_occ = 0;
data.slots_down.map(function(v, i){
if(data.occupied_slots.indexOf(v) === -1){
down_but_not_occ ++;
};
})
var available_slots = parseInt(data.total_slots) - data.occupied_slots.length - down_but_not_occ;
console.log(available_slots);

你错了,
total_slots = parseInt(total_slots) - parseInt(SLOTS_DOWN); // slots down subtracted
var occupied = s.occupied_count;
var available = parseInt(total_slots) - parseInt(occupied) - parseInt(SLOTS_DOWN); // slots down AGAIN subtracted