如何将项数组转换/旋转到JavaScript数组中的特定索引? [英] How to shift/rotate an array of items to a specific index in a JavaScript array?

查看:74
本文介绍了如何将项数组转换/旋转到JavaScript数组中的特定索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery元素集合(图像)。

I have a jQuery collection of elements (images).

var images = $('img');

我想改变集合,使其从特定索引开始,并附加前面的项目到最后。有点像 Rolodex

I want to alter the collection so that it starts at a specific index, and the previous items are appended to the end. Sort of like a Rolodex.

如有必要,我也可以将它们转换为数组。使用JavaScript数组的一个示例:

I could also convert them to an array if necessary. An example of this with a JavaScript array:

var images = ['image0', 'image1', 'image2', 'image3'];
// rotate through to index 2
// images should == ['image2', 'image3', 'image0', 'image1']


推荐答案

对于数组,你可以这样做:

For the Array, you could do this:

images.push.apply(images, images.splice(0, i));

var images = ['image0', 'image1', 'image2', 'image3'];
var i = 2;


images.push.apply(images, images.splice(0, i));


document.body.textContent = images.join(",");

有多少项可以传递给 .apply(),但它数以千计。如果这是一个问题,那么您可以从 .splice()中推送单个项目。

There's a limit to how many items can be passed to .apply(), but it's in the thousands. If that's an issue, then you can push individual items from the .splice() in.

这篇关于如何将项数组转换/旋转到JavaScript数组中的特定索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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