Object insert issue in JavaScript array

This question already has an answer here:

  • How to insert an item into an array at a specific index? 10 answers

  • 喜欢这个:

    var a = [
        {type: 'text', name: 'title', id: 'title', placeholder: 'Type here'},
        {type: 'textarea', name: 'description', id: 'description', placeholder: 'Type here'}
    ]
    
    var b= {type: 'text', name: 'age', id: 'age', placeholder: 'Type here'} 
    
    a.splice(1,0,b);
    
    console.log(a)
    

    If your array is in variable array , then:

    array.splice(1, 0, {
        type: 'text',
        name: 'age',
        id: 'age',
        placeholder: 'Type here'
    });
    

    The 1 means that you want to place it at index 1 , 0 means you want to delete 0 items from the array. See splice documentation, it is quite the abomination of a method with 2 purposes of which both are never used at the same time :D


    如果您想在该确切位置使用该对象,请使用splice方法。

    var myArray = [{
      type: 'text',
      name: 'title',
      id: 'title',
      placeholder: 'Type here'
    }, {
      type: 'textarea',
      name: 'description',
      id: 'description',
      placeholder: 'Type here'
    }];
    var myObject = {
      type: 'text',
      name: 'age',
      id: 'age',
      placeholder: 'Type here'
    };
    myArray.push(myObject);
    
    链接地址: http://www.djcxy.com/p/29310.html

    上一篇: 将数据推入数组中的某个位置

    下一篇: JavaScript数组中的对象插入问题