Problem 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 should remove all elements from the array "arrayElements". But it will not be.

The Javascript engine supports it "index"as it is, and does not have against the modified array. People can expect something like a loop "for each"that doesn't have such a problem.

even the following code does not work:

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

even when changing the value of the variable "index" does not seem to work. the changed value is available inside the "for (...) {...}" block, but since the loop reaches the next iteration, the value gets reset and continues from the next index as a clock mechanism.

therefore, it seems that such code 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.

"splice()", , .

"W3C" , , .

+5
2

John Resig array.remove() .

// 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);
};
+2

:

* Splice , tge loop . *

var arrayElements = ["elem1","elem2","elem3","elem4"];
arrayElements.splice(0,arrayElements.length);
alert("Elements: "+arrayElements)
0

All Articles