Showing posts from August, 2010

Using javascript array function splice to modify array contents

Javascript array object has lots of pre-defined functions that makes life easy. Among them, splice is the method lot of developers are not aware of.
Using splice, you can remove an element in array, replace array contents without copying, iterating through entire elements. Prototype uses existence of splice method to identify whether an object is an array or not (Object.isArray). so, no need to worry about browser compatibilities.
I used to iterate through entire array object to remove an element like the following
var arrObj = ['1', '4', '3', '2']; var anotherArray = []; for (var i = 0;i <=arrObj.length; i++) { if(arrObj[i] != '3') { anotherArray.push(arrObj[i]); } }
We need to iterate through entire array to remove an element if above method is followed. Using splice method,

var arrObj = ['1', '4', '3', '2']; for(var i = 0;i <=arrObj.length; i++) { if(arrObj[i] == '3') { arr…