Javascript 如何更改数组中特定项的位置?
我试图更改一个项目在数组中的索引位置,但我想不出一个方法Javascript 如何更改数组中特定项的位置?,javascript,arrays,Javascript,Arrays,我试图更改一个项目在数组中的索引位置,但我想不出一个方法 { "items": [ 1, 3, 2 ] } 若要按Unicode顺序(数字变成字符串)对它们进行排序,可以使用函数 items.sort(); function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is grea
{
"items": [
1,
3,
2
]
}
若要按Unicode顺序(数字变成字符串)对它们进行排序,可以使用函数
items.sort();
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
如果您有自定义订单,则需要为排序函数提供排序函数
items.sort();
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
你是这样使用它的:
items.sort(compare(a, b));
可以使用移动数组中的元素:
var arr = [
1,
3,
2
];
var oldIndex = 2,
newIndex = 1;
arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
这使得[1,2,3]
内部接头将删除并返回图元,而外部接头将其插入
为了好玩,我定义了一个通用函数,它可以移动一个切片,而不仅仅是一个元素,并计算索引:
Object.defineProperty(Array.prototype, "move", {
value:function(oldIndex, newIndex, nbElements){
this.splice.apply(
this, [newIndex-nbElements*(newIndex>oldIndex), 0].concat(this.splice(oldIndex, nbElements))
);
}
});
var arr = [0, 1, 2, 7, 8, 3, 4, 5, 6, 9];
arr.move(5, 3, 4);
console.log('1:', arr) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var arr = [0, 1, 2, 7, 8, 3, 4, 5, 6, 9];
arr.move(3, 9, 2);
console.log('2:', arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var arr = [0, 1, 2, 4, 5, 3, 6, 7];
arr.move(5, 3, 1);
console.log('3:', arr); // [0, 1, 2, 3, 4, 5, 6, 7]
var arr = [0, 3, 1, 2, 4, 5, 6, 7];
arr.move(1, 4, 1);
console.log('3:', arr); // [0, 1, 2, 3, 4, 5, 6, 7]
您想更改哪个索引???预期的输出是什么?我希望将数组更改为
“items”:[1,2,3]
解析此Json并获取数组,然后根据需要更改索引。@SalmanA当数组较大时,您无法通过交换解决移动问题。我希望能够更改items索引,不根据它们的值对它们进行排序。@MichaelWilson2013我不确定我是否理解:您想要类似于sort()
的东西,但它只对索引有效,而不是对值有效?这到底是如何工作的?为什么在拼接
中有一个拼接
?我非常喜欢通用功能!:P@MichaelWilson2013我看过你的编辑。这不是更清楚吗:?是的,更清楚了,谢谢你的帮助!虽然如果我们失去了输出: