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

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

    Here's a working function that I uses in one of my application.

    This checks if item exit

    let ifExist = (item, strings = [ '' ], position = 0) => {
         // output into an array with empty string. Important just in case their is no item. 
        let output = [ '' ];
        // check to see if the item that will be positioned exist.
        if (item) {
            // output should equal to array of strings. 
            output = strings;
           // use splice in order to break the array. 
           // use positition param to state where to put the item
           // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position. 
            output.splice(position, 0, item);
        }
        //empty string is so we do not concatenate with comma or anything else. 
        return output.join("");
    };
    

    And then I call it below.

    ifExist("friends", [ ' ( ', ' )' ], 1)}  // output: ( friends )
    ifExist("friends", [ ' - '], 1)}  // output:  - friends 
    ifExist("friends", [ ':'], 0)}  // output:   friends: 
    

提交回复
热议问题