Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Javascript For loop

Consider the Code below:

function splicer()
{
 var arrayElements = ["elem1","elem2","elem3","elem4"];
 for(var index in arrayElements)
 {
  arrayElements.splice(index,1);
 }
 alert("Elements: "+arrayElements);
}

The above function is supposed to remove all the elements from the array "arrayElements". But it won't.

Javascript engine maintains the "index" as it is and doesn't mind the array being modified. People might expect something like "for each" loop that doesn't have this kind of issue

even the following code doesn't seem to work:

function splicer()
{
...
 for(var index in arrayElements)
 {
  arrayElements.splice(index--,1);
 }
...
}

even when changing the value of the variable "index" doesn't seem to work. the changed value is available inside the "for(...){...}" block but, as the loop reaches the next iteration, the value gets reset and continues from the next index as clockwork.

so it seems code like this might be the only solution:

function splicer()
{
 var arrayElements = ["elem1","elem2","elem3","elem4"];
 for(var index=0;index<arrayElements.length;index++)
 {
  arrayElements.splice(index--,1);
 }
 alert("Elements: "+arrayElements);
}

Tested in: Firefox 16 Beta.

But placing a unary Operator inside a "splice()" method seems to be misleading at first sight.

This might be worth considering to the "W3C" or whomever it may concern so that they come up with a nice solution.

like image 970
Nokia808Freak Avatar asked Nov 04 '22 15:11

Nokia808Freak


1 Answers

You may want to refer to John Resig's array.remove() link.

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
like image 153
Konstantin Dinev Avatar answered Nov 15 '22 00:11

Konstantin Dinev