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

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

    Anyone who's still having issues with this one and have tried all the options above and never got it. I'm sharing my solution, this is to take consideration that you don't wan't to explicitly state the properties of your object vs the array.

    function isIdentical(left, right){
        return JSON.stringify(left) === JSON.stringify(right);
    }
    
    function contains(array, obj){
        let count = 0;
        array.map((cur) => {
              if(this.isIdentical(cur, obj)) count++;
        });
        return count > 0;
    }
    

    This is a combination of iterating the reference array and comparing it to the object you wanted to check, convert both of them into a string then iterated if it matched. Then you can just count. This can be improved but this is where I settled. Hope this helps.

提交回复
热议问题