3 回答

TA貢獻1844條經驗 獲得超8個贊
如果您不在乎原始數組,則只需使用shift下一個門即可(shift將從陣列中刪除該門,因此當再次遇到該對象時,下一個門將可用)。用于find從數組中查找對象:
let result = mapsOrder.map(id =>
mapData.find(o => o.id == id).gates.shift().coords
);
您可能想find在使用之前檢查是否確實找到了某些東西,并且gates數組包含某些東西shift,這是一種更安全的方法:
let result = mapsOrder.map(id => {
let obj = mapData.find(o => o.id == id);
if(obj && obj.gates.length) { // if we found an object with the same id and that object still have gates
return obj.gates.shift().coords; // return the coords of the first gate and remove the gate from the array
} // otherwise, throw an error or something
});
不可更改:
而不是使用shift前面的示例,我們將使用一個對象來跟蹤gates數組中的門索引:
let nextGateIndex = Object.create(null); // create a prototypeless object to track the next gate index for each object
let result = mapsOrder.map(id => {
let obj = mapData.find(o => o.id == id);
let index;
if(nextGateIndex[id] == undefined) {
index = 0;
} else {
index = nextGateIndex[id] + 1;
}
nextGateIndex[id] = index;
if(obj && index < obj.gates.length) {
return obj.gates[index].coords;
} // throw error or something
});

TA貢獻1785條經驗 獲得超8個贊
如果按照您的描述,您的循環應類似于。似乎您要使用id和toId使用數組索引。用對象替換數組可能是一個好主意。
for(let i = 0; i < mapsOrder.length; i++) {
let nextMap;
let currentMapId = mapsOrder[i];
if(i === mapsOrder.length - 1) {
nextMapId = mapsOrder[0]
} else {
nextMapId = mapsOrder[i + 1];
}
let filteredMapData = mapData.filter(f => f.id == currentMapId);
let filteredGates = filteredMapData.length > 0 ? filteredMapData[0].gates.filter(f => f.toId == nextMapId) : [];
console.log('Current map is: ', currentMapId, 'and the next map id is:', nextMapId, 'gates:', filteredGates.length == 0 ? "no gates": filteredGates[0].coords)
console.log('break----')
}
添加回答
舉報