,数组出来我已经得到了我想要基于重新排序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