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----')
}
添加回答
举报