简体   繁体   中英

Array.Splice prototype

I have a addAfter and addBefore function that adds a new element to an array. This array is my storage that other functions use. Basically I am storing low level objects that define table cells. After the element is added to the array I then have to insert the value of the html property of the element the table row.

Is there a way to prototype my array to handle both operations rather than me having to double up on the work load every time I addAfter or addBefore, with-out messing up the prototype of the native array?

var bays=[];

 addAfter: function (b, n) {
            for (var i = 0, ii, len = bays.length; i < len; i++) {
                ii = i + 1; if (ii == n) {
                    bays.splice(ii, 0, b);
                    var newCell = canvsTrBay.insertCell(ii);
                    newCell.outerHTML = b._html;
                };
            };
            this.build();
        }

Is it possible to do something like:

   bays.prototype.add=function(b,n,isAfter){

       for (var i = 0, ii, len = bays.length; i < len; i++) {
                    ii =(isAfter? (i + 1):(n>0?i-1:0); 
                     if (ii == n) {
                        bays.splice(ii, 0, b);
                        var newCell = canvsTrBay.insertCell(ii);
                        newCell.outerHTML = b._html;
                    };
                };
                this.build();
    }

您可以将其直接添加到对象本身:

bays.add = ...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM