javascript change elements in array

This question already has an answer here:

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

  • If I understood you right, the problem for you is to how to insert and move elements in array. You can do it with splice method, which has optional parameters for elements to insert:

    Here is what you need for your example:

    var myArray = [
      {name: "not selected"}, 
      {name: "not selected"},
      {name: "selected"}, 
      {name: "not selected"},
      {name: "not selected"}, 
      {name: "not selected"}
    ];
    
    myArray.splice(3, 0, {
      name: "new element"
    });
    console.log(myArray);

    你可以使用Array#splice并在元素被插入到数组之后获取一个索引。

    var array = [{ name: "not selected" }, { name: "not selected" }, { name: "selected" }, { name: "not selected" }, { name: "not selected" }, { name: "not selected" }],
        index = 2,
        item = { name: "new element" };
    
    array.splice(index + 1, 0, item);
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    链接地址: http://www.djcxy.com/p/29316.html

    上一篇: 如何将新项目“推”到数组中间?

    下一篇: 数组中的javascript更改元素