重新排序数组 [英] Reordering arrays

查看:37
本文介绍了重新排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,我有一个看起来像这样的数组:

var 播放列表 = [{艺术家:赫比·汉考克",标题:推力"},{艺术家:Lalo Schifrin",标题:变速齿轮"},{艺术家:Faze-O",标题:骑高"}];

如何将元素移动到另一个位置?

例如,我想将 {artist:"Lalo Schifrin", title:"Shifting Gears"} 移到最后.

我尝试使用 splice,如下所示:

var tmp = playlist.splice(2,1);playlist.splice(2,0,tmp);

但它不起作用.

解决方案

Say, I have an array that looks like this:

var playlist = [
    {artist:"Herbie Hancock", title:"Thrust"},
    {artist:"Lalo Schifrin", title:"Shifting Gears"},
    {artist:"Faze-O", title:"Riding High"}
];

How can I move an element to another position?

I want to move for example, {artist:"Lalo Schifrin", title:"Shifting Gears"} to the end.

I tried using splice, like this:

var tmp = playlist.splice(2,1);
playlist.splice(2,0,tmp);

But it doesn't work.

解决方案

The syntax of Array.splice is:

yourArray.splice(index, howmany, element1, /*.....,*/ elementX);

Where:

  • index is the position in the array you want to start removing elements from
  • howmany is how many elements you want to remove from index
  • element1, ..., elementX are elements you want inserted from position index.

This means that splice() can be used to remove elements, add elements, or replace elements in an array, depending on the arguments you pass.

Note that it returns an array of the removed elements.

Something nice and generic would be:

Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

Then just use:

var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5

Diagram:

这篇关于重新排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆