Using splice method from zArray Library 2 : Splice « Array « JavaScript Tutorial






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
    <head>
        <title>splice() Example 2</title>
        <script type="text/javascript">
/*------------------------------------------------------------------------------
 * JavaScript zArray Library
 * Version 1.1
 * by Nicholas C. Zakas, http://www.nczonline.net/
 * Copyright (c) 2004-2005 Nicholas C. Zakas. All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *------------------------------------------------------------------------------
 */ 

var aCheckMethods = new Array("concat", "push", "pop", "every", "some", "forEach",
                              "filter", "map", "indexOf", "lastIndexOf", "slice",
                              "splice", "shift", "unshift");


/**
 * Appends any number of items onto the end of the array.
 */
Array.prototype.append = function () {
    for (var i=0; i < arguments.length; i++) {
        this[this.length] = arguments[i];
    }
};

/**
 * Creates a copy of the array and returns it.
 * @return A copy of the array.
 */
Array.prototype.clone = function () /*:Array*/ {
    return this.concat();
};

/**
 * Determines if a given item is in the array.
 * @param vItem The item to insert.
 * @return True if found, false if not.
 */
Array.prototype.contains = function (vItem /*:variant*/) /*:boolean*/ {
    return this.indexOf(vItem)>-1;
};


/**
 * Runs a function on each item in the array and returns a result.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param fnTest The function to run on each value.
 * @param oThis The object that the function belongs to or null for a global 
 *              function. 
 * @return True if the function evaluates to true for each item in the array,
 *         false if even one returns false.
 */
Array.prototype._every = function (fnTest /*:Function*/, oThis /*:Object*/)/*:boolean*/ {

    if (this.length > 0) {
        var bResult = true;

        oThis = oThis || window;
        oThis.__everyFunc__ = fnTest;
        
        for (var i=0, l=this.length; i < l && bResult; i++) {
            bResult = bResult && oThis.__everyFunc__(this[i], i, this);
        }
        
        oThis.__everyFunc__ = null;
        
        return bResult;
    } else {
        return true;   //fix(1.02): changed from false
    }
};

/**
 * Runs a function on each item and returns an array.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param fnTest The function to run on each item.
 * @param oThis The object that the function belongs to or null for a global 
 *              function.
 * @return An array made up of all the items that returned true for the function.
 */
Array.prototype._filter= function (fnTest /*:Function*/, oThis /*:Object*/)/*:Array*/ {
    
    var aResult /*:Array*/ = new Array();
    oThis = oThis || window;
    oThis.__filterFunc__ = fnTest;
    
    for (var i=0, l=this.length; i < l; i++) {
        if (oThis.__filterFunc__(this[i], i, this)) {
           aResult.push(this[i]);
        }
    }
    
    oThis.__filterFunc__ = null;
    
    return aResult;
};

/**
 * Runs a function on each item in the array and returns a result.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param fnExec The function to run on each value.
 * @param oThis The object that the function belongs to or null for a global 
 *              function.
 */
Array.prototype._forEach = function (fnExec /*:Function*/, oThis /*:Object*/) {
    
    oThis = oThis || window;
    oThis.__forEachFunc__ = fnExec;
    
    for (var i=0, l=this.length; i < l; i++) {
        oThis.__forEachFunc__(this[i], i, this);
    }
    
    oThis.__forEachFunc__ = null;

};

/**
 * Returns the index of the first occurrance in the array.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param vItem The item to locate in the array.
 * @param iStart The item to start looking from (optional). 
 * @return The index of the item in the array if found or -1 if not found.
 */
Array.prototype._indexOf = function (vItem /*:Variant*/, iStart /*:int*/)/*:int*/ {
    if (iStart == null) {
        iStart = 0;
    }
    
    for (var i=iStart, l=this.length; i < l; i++) {
        if (this[i] == vItem) {
            return i;
        }
    }
    return -1;
};

/**
 * Inserts an item into the array at the given position.
 * @param vItem The item to insert.
 * @param iIndex The index to insert the item into.
 */
Array.prototype.insertAt = function (vItem /*:variant*/, iIndex /*:int*/) /*:variant*/ {
    this.splice(iIndex, 0, vItem);
};

/**
 * Inserts an item into the array before the given item.
 * @param vItem The item to insert.
 * @param vBeforeItem The item to insert before.
 */
Array.prototype.insertBefore = function (vItem /*:variant*/, vBeforeItem /*:variant*/) /*:variant*/ {
    this.insertAt(vItem, this.indexOf(vBeforeItem));
};

/**
 * Returns the last index of the first occurrance in the array.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param vItem The item to locate in the array.
 * @param iStart The index of the item to start at.
 * @return The last index of the item in the array if found or -1 if not found.
 */
Array.prototype._lastIndexOf = function (vItem /*:Variant*/, iStart /*:int*/)/*:int*/ {
    if (iStart == null || iStart >= this.length) {
        iStart = this.length-1;
    }
    
    for (var i=iStart; i >= 0; i--) {
        if (this[i] == vItem) {
            return i;
        }
    }
    return -1;
};

/**
 * Runs a function on each item and returns an array.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param fnExec The function to run on each item.
 * @param oThis The object that the function belongs to or null for a global
 *              function.
 * @return An array made up of all the items that returned true for the function.
 */
Array.prototype._map = function (fnExec /*:Function*/, oThis /*:Object*/)/*:Array*/ {
    
    var aResult /*:Array*/ = new Array();
    oThis = oThis || window;
    oThis.__mapFunc__ = fnExec;
    
    for (var i=0, l=this.length; i < l; i++) {
        aResult.push(oThis.__mapFunc__(this[i], i, this));
    }
    
    oThis.__mapFunc__ = null;
    
    return aResult;
};

/**
 * Pops off the last item in the array and returns it.
 * Defined in ECMA-262 3rd Edition.
 * @return The last item in the array.
 */
Array.prototype._pop = function ()/*:variant*/ {

    var oItem /*:Variant*/ = null;
    
    if (this.length > 0) {
        oItem = this[this.length-1];
        this.length--;
    }
    
    return oItem;
};

/**
 * Pushes any number of items onto the end of the array.
 * Defined in ECMA-262 3rd Edition.
 */
Array.prototype._push = Array.prototype.append;

/**
 * Removes the array item matching the given item.
 * @param vItem the item to remove.
 * @return The removed item.
 */
Array.prototype.remove = function (vItem /*:variant*/) /*:variant*/ {
    this.removeAt(this.indexOf(vItem));    
    return vItem;
};

/**
 * Removes the array item in the given position.
 * @param iIndex The index of the item to remove.
 * @return The removed item.
 */
Array.prototype.removeAt = function (iIndex /*:int*/) /*:variant*/ {
    var vItem = this[iIndex];
    if (vItem) {
        this.splice(iIndex, 1);
    }
    return vItem;
};

/**
 * Creates an array composed of the indicated items in the current array.
 * Defined in ECMA-262 3rd Edition.
 * @param iStart The first item to copy.
 * @param iStop The index after the last item to copy.
 * @return An array containing all items in the original array between the given
 *         indices.
 */
Array.prototype._slice = function (iStart /*:int*/, iStop /*:int*/)/*:Array*/ {
 
    var aResult /*:Array*/ = new Array();
    iStop = iStop || this.length;
    
    for (var i=iStart; i < iStop; i++) {
        aResult.push(this[i]);
    }
    
    return aResult;
};

/**
 * Removes the first item in the array and returns it.
 * Defined in ECMA-262 3rd Edition.
 * @return The first item in the array.
 */
Array.prototype._shift = function ()/*:variant*/ {
 
    var vItem = this[0];
    if (vItem) {
        this.splice(0,1);
    }
    return vItem;
};

/**
 * Runs a function on each item in the array and returns a result.
 * Defined in Mozilla 1.8 Core JavaScript
 * @param fnTest The function to run on each value.
 * @return True if the function evaluates to true for any one item, false if not.
 */
Array.prototype._some= function (fnTest /*:Function*/, oThis /*:Object*/)/*:boolean*/ {
    
    oThis = oThis || window;
    oThis.__someFunc__ = fnTest;
    
    for (var i=0, l=this.length; i < l; i++) {
        if (oThis.__someFunc__(this[i], i, this)) {
           return true;
        }
    }
    
    oThis.__someFunc__ = null;
    
    return false;
};

/**
 * Alters the array by removing specified items and inserting others.
 * Defined in ECMA-262 3rd Edition.
 * @param iIndex The index at which to begin altering the array.
 * @param iLength The number of items to remove.
 * @param vItem[] The items to insert in place of the removed items.
 * @return An array containing all removed items.
 */
Array.prototype._splice = function (iIndex /*:int*/, iLength /*:int*/)/*:Array*/ {
 
    var aResult /*:Array*/ = new Array();
    var aRemoved /*: Array */ = new Array();
    
    for (var i=0; i < iIndex; i++){
        aResult.push(this[i]);
    }
    
    for (var i=iIndex; i < iIndex+iLength; i++) {
       aRemoved.push(this[i]);
    }
    
    if (arguments.length > 2) {
        for (var i=2; i < arguments.length; i++) {
            aResult.push(arguments[i]);
        }
    }

    for (var i=iIndex+iLength; i < this.length; i++) {
        aResult.push(this[i]);
    }
    
    for (var i=0; i < aResult.length; i++) {
        this[i] = aResult[i];
    }
    this.length = aResult.length;
    
    return aRemoved;
};

/**
 * Adds all the items in the array and returns the result.
 * @param fnConvert An optional function to run on each item before adding.
 * @param oThis The object that the function belongs to or null for a global 
 *              function. 
 * @return The result of adding all of the array items together.
 */
Array.prototype.sum = function (fnConvert /*:Function*/, oThis /*:Object*/)/*:variant*/ {

    if (this.length > 0) {
        var vResult = null;

        oThis = oThis || window;
        oThis.__sumFunc__ = fnConvert || function (vVal) { return vVal; };
        
        vResult = oThis.__sumFunc__(this[0], 0, this);
        
        for (var i=1, l=this.length; i < l; i++) {
            vResult += oThis.__sumFunc__(this[i], i, this);
        }
        
        oThis.__sumFunc__ = null;
        
        return vResult;
    } else {
        return null;
    }
};

/**
 * Places the given items at the beginning of the array.
 * Defined in ECMA-262 3rd Edition.
 * @param vItem[] Items to add into the 
 */
Array.prototype._unshift = function () {
    var sExec = "this.splice(";
    
    var aArgs = new Array();
    for (var i=0,l=arguments.length; i < l; i++) {
        aArgs.push("arguments["+i+"]");
    } 
    
    eval("this.splice(0,0," + aArgs.join(",") + ")");
};

/*
 * Assign the necessary methods.
 */
for (var i=0; i < aCheckMethods.length; i++) {
    if(!Array.prototype[aCheckMethods[i]]) {
        Array.prototype[aCheckMethods[i]] = Array.prototype["_"+aCheckMethods[i]];
    }
}


        </script>
    </head>
    <body>        
        <h1>splice() Example 2</h1>
        <script type="text/javascript">
           var aNumbers = [2, 5, 9];
           var aRemoved = aNumbers.splice(1, 2, 100, 200, 300);  //remove 5, 9, insert 100, 200, 300
           alert("aNumbers is [" + aNumbers + "]");
           alert("aRemoved is [" + aRemoved + "]");


        </script>
        <P>This example defines an array [2, 5, 9] then removes the 5 and 9, inserting
        100, 200, and 300 in their place.</p>   
    </body>
</html>








11.30.Splice
11.30.1.Array.splice()
11.30.2.Using the splice() method of the Array object
11.30.3.Using the splice() method to replace elements
11.30.4.Using the splice() method to insert elements
11.30.5.Using splice method from zArray Library
11.30.6.Using splice method from zArray Library 2