简体   繁体   中英

Pick specific elements from array

I hava an array with 17 images. I want to pick every image from the array and put it on the stage but there should be a specific manner to do this. After I picked the first image I need the nith one so this should look like this:

var myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; // these are the indexes for the 17 images

The order to pick the elemets looks like this : [0,9,1,10,2,11,3,12,4,13,5,14,6,15,7,16,8];

I need to use them in a Tween , this is the function where I am doing this but I do not have the oder I mentioned above.

var pick_images = function(lights_arr,iterator,f)
{
  if(iterator < lights_arr.length)
  {
    iterator = iterator +1;
  }
    createjs.Tween.get(lieghts_arr[iterator]).to({alpha:0},200).wait(0).to({alpha:1},200).wait(100).call([f,lights_arr,f]);
pick_images(arr, i,pick_images);

I know that if I take the lights_arr.length and divide it by 2, round it up I have allways the second image like 9,10,11 or 12. For this I need after every loop to substract two elemets ( images ) I used.

Do you know how can I do this to work in my function ?

How about this?

var myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

var select = [];
var step = 9;
var len = myarray.length;
for(var i = 0; i < len * step; i += step)
    select.push(myarray[i % len])

console.log(select) // [ 0, 9, 1, 10, 2, 11, 3, 12, 4, 13, 5, 14, 6, 15, 7, 16, 8 ]

Just extended/optimised georg's code a bit to make it more dynamic because I think his is a pretty neat solution:

var len = 17,
    myarray = Array.apply(null, {length: len}).map(Number.call, Number),
    select = [],
    step = Math.round(myarray.length / 2);

for(var i = 0; i < len * step; i += step) {
  select.push(myarray[i % len]);
}

console.log(select);

Here 's the code to generate an array filled with integers.

var switch = false;
var selectedIndex = 0;
if(i < arr.length)
{
    selectedIndex = (switch) ? i : i + 9; 
    switch = !switch;
}

Something like that should do it, could probably be done neater though. Note, untested and on the top of my popo.

Edit: oh and for the images you want removed you can use splice:

var arr = [0,1,2];
arr.splice(1,1); // position and how many to remove

output: arr = [0,2];

splice w3c documentation

var myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var select = [];
var position = 0;
while (position < myarray.length) {
  select.push(myarray[position]);
  if (select.length % 2) position += 9;
  else position -= 8;
}
alert(select);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM