,數組出來我已經得到了我想要基於重新排序JavaScript數組
我已經試過兩種不同的方法,到目前爲止項目的數組中的索引重新秩序,但它似乎一個數組只是當它在發送數據的
function orderPlayers(players, fpIndex){
for(var i = 0; i < players.length; i ++){
players.move(i, fpIndex);
fpIndex = fpIndex + 1;
if(fpIndex > players.length - 1){fpIndex = 0;}
}
return players;
}
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
例:
fpIndex: 1 //The player that is first is at array index 1
Players: {
player: {
age: 19,
name: Bob,
piece: "red",
isFirst: false
}
player: {
age: 21,
name: Steve,
piece: "blue",
isFirst: true
}
}
應該站出來爲:
Players: {
player: {
age: 21,
name: Steve,
piece: "blue",
isFirst: true
}
player: {
age: 19,
name: Bob,
piece: "red",
isFirst: false
}
}
可以爲用戶提供的輸入和預期輸出的例子嗎? – abagshaw
好的,希望對你有所幫助 –
是否只是將一個元素從指定的索引移動到數組的開頭?您不需要循環,只需使用一次調用'.splice()'將其刪除,再加上一次調用'.unshift()'來插入它。 – nnnnnn