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

后端 未结 20 2145
灰色年华
灰色年华 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:43

    Another possible solution, with usage of Array#reduce.

    const arr = ["apple", "orange", "raspberry"];
    const arr2 = [1, 2, 4];
    
    const insert = (arr, item, index) =>
      arr.reduce(function(s, a, i) {
        i === index ? s.push(item, a) : s.push(a);
        return s;
      }, []); 
    
    console.log(insert(arr, "banana", 1));
    console.log(insert(arr2, 3, 2))

提交回复
热议问题