我有一个数组,我想根据数组中项目的索引重新排序
到目前为止,我尝试了两种不同的方法,但似乎数组的发布方式与发送时一样。
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
}
}
答案 0 :(得分:0)
所以你想要反转数组?你试过Array.prototype.reverse()吗?
答案 1 :(得分:0)
这是你在找什么?见工作示例:
var players =
{
"Players":
[
{
"player": {
"age": 21,
"name": "Steve",
"piece": "blue",
"isFirst": true
}
},
{
"player": {
"age": 19,
"name": "Bob",
"piece": "red",
"isFirst": false
}
}
]
}
var fpIndex = 1;
function orderPlayers(plys, index){
index = index % plys.length;
if(plys.length === 0 || plys.length === 1 || index === 0){
return plys;
}
let part = plys.splice(plys.length - index);
return part.concat(plys);
}
console.log(orderPlayers(players.Players, fpIndex));
&#13;