Jump to content

[SOLVED] NOT change indexes when using Splice()?


galvin

Recommended Posts

If you have an array with 10 elements and you use splice() to remove the 3rd element (index of 2), it changes the index of all the ones after the one you removed.

 

Is there a way to make it so the indexes do NOT change at all?

 

So if I had an array of....

 

var arr = new Array(10);

arr[0] = "Jani";

arr[1] = "Hege";

arr[2] = "Stale";

arr[3] = "Jim";

arr[4] = "Borge";

arr[5] = "Mike";

arr[6] = "Joe";

arr[7] = "Cathy";

arr[8] = "Sarah";

arr[9] = "Lauren";

 

ANd then I use splice() to remove "Jim", I'd like the array to now be...

 

arr[0] = "Jani";

arr[1] = "Hege";

arr[2] = "Stale";

 

arr[4] = "Borge";

arr[5] = "Mike";

arr[6] = "Joe";

arr[7] = "Cathy";

arr[8] = "Sarah";

arr[9] = "Lauren";

 

There's gotta be a way, right?

could you instead overwrite that array?

 

so arr[3] = '';

 

What specifically u looking for?

 

Or you could try:

 

var max_array = arrayMaximum(arr[]);

var array_split_value = 3;

 

for(z = array_split_value; z < max_array; z++)

{

  arr[z] = arr[z+1];

}

 

You might not be able to do that exactly as Iv done it, im not familiar with js.

I can't make it "undefined" because I need to continue to display the array values on the webpage.  After setting them to "undefined", they then display the actual word "undefined" on the page.  Good idea, but it won't work for my purposes unfortunately.

 

I feel like there has to be a way to tell javascript to NOT change the array indexes even after you remove one using Splice(), but I am not familiar enough with Javascript to know how.

 

If anyone else has any ideas let me know.

 

Thanks,

Greg

I don't know how you're printing it out, but you should do something like this:

 

var e = new Array();
e[3] = 4;

var start = 0;
while (e[start++] !== undefined) {
     document.body.innerHTML += e[start];
}

 

Do know that it's an infinite loop. It's just for hints.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.