How to push to an array in a particular position?

前端 未结 3 1064
闹比i
闹比i 2020-12-30 01:35

I\'m trying to efficiently write a statement that pushes to position 1 of an array, and pushes whatever is in that position, or after it back a spot.

array =         


        
相关标签:
3条回答
  • 2020-12-30 01:59

    The splice() function is the only native array function that lets you add elements to the specific place of an array

    I will get a one array that you entered in your question to describe

    splice(position, numberOfItemsToRemove, item)
    
    • position = What is the position that you want to add new item
    • numberOfItemsToRemove = This indicate how many number of items will deleted. That's mean delete will start according to the position that new item add.

    Ex = if you want to add 1 position to 123 result will be like this ([4,123,0,5,9,6,2,5]) but if you give numberOfItemsToRemove to 1 it will remove first element after the 123 if you give 2 then its delete two element after 123.

    • item = the new item that you add

    function my_func(){
            var suits = [4,0,5,9,6,2,5]
            
            suits.splice(1 , 0 , 123);
    
            document.getElementById('demo').innerHTML = suits;
    }
    <button id="btn01" onclick="my_func()">Check</button>
    <p id="demo"></p>

    0 讨论(0)
  • 2020-12-30 02:06
    array = [4,5,9,6,2,5]
    
    #push 0 to position 1
    array.splice(1,0,0)
    
    array = [4,0,5,9,6,2,5]
    
    #push 123 to position 1
    array.splice(1,0,123)
    
    array = [4,123,0,5,9,6,2,5]
    
    0 讨论(0)
  • 2020-12-30 02:09

    To push any item at specific index in array use following syntax

    // The original array
    var array = ["one", "two", "four"];
    // splice(position, numberOfItemsToRemove, item)
    array.splice(2, 0, "three");
    
    console.log(array);  // ["one", "two", "three", "four"]
    
    0 讨论(0)
提交回复
热议问题