How to insert an item into an array at a specific index (JavaScript)?

后端 未结 20 2496
灰色年华
灰色年华 2020-11-21 07:05

I am looking for a JavaScript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any JavaScript implem

20条回答
  •  没有蜡笔的小新
    2020-11-21 07:54

    i like little safety and i use this

       Array.prototype.Insert = function (item, before) {
            if (!item) return;
            if (before == null || before < 0 || before > this.length - 1) {
                this.push(item);
                return;
            }
            this.splice(before, 0,item );
        }
        
        
       var t = ["a","b"]
       
       t.Insert("v",1)
        
        console.log(t )

提交回复
热议问题