search

Home  >  Q&A  >  body text

javascript - Can't data be inserted into the middle of a nodejs list?

Lists in Python can insert data in the middle:

>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.insert(3,10)
>>> a
[1, 2, 3, 10, 4, 5, 6, 7]

But there seems to be no insert function in nodejs, and deleting the middle elements is not complete.

> a= [1, 2, 3, 4, 5, 6]
[ 1,
  2,
  3,
  4,
  5,
  6 ]
> delete a[2]
true
> a
[ 1,
  2,
  ,
  4,
  5,
  6 ]
  1. If you want to delete a[2] and get a new list of [1,2,4,5,6,7], what should you do?

  2. If you want to insert data 10 after the third position and get [1,2,3,10,4,5,6], what should you do?

某草草某草草2777 days ago630

reply all(4)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:45:43

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:45:43

    a.splice(2,1);
    a.splice(3,0,10);

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:45:43

    Correct answer upstairs

    a.splice(2,1); //从a数组中第3个元素(下标2)开始删除,删掉一个。 这时a数组会发生变化
    a.splice(3,0,10);  //从a数组中第4个(下标3)元素开始删除,删除0个, 并把10插入到这个元素之前。

    Attached is the usage of splice

    The

    splice() method adds/removes items to/from the array and returns the removed item.
    Note: This method will change the original array.

    Grammar

    arrayObject.splice(index,howmany,item1,.....,itemX)
    • index required. An integer specifying the position at which to add/remove an item. Use a negative number to specify the position from the end of the array.

    • howmany required. The number of items to delete. If set to 0, items will not be deleted.

    • item1, ..., itemX optional. New items added to the array.

    Return Value
    Array A new array containing the deleted items, if any.

    Description
    The splice() method removes zero or more elements starting at index and replaces those removed elements with one or more values ​​declared in the parameter list.
    If an element is deleted from arrayObject, the array containing the deleted element is returned.

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-16 13:45:43

    The original poster didn’t know the power of splice. splice(start,deleteCount,val1,val2,...):Delete the deleteCount item from the start position, and insert val1, val2,... from this position. You can extend the prototype method of Array yourself:

    Array.prototype.insert = function (index, item) {  
      this.splice(index, 0, item);  
    };

    This way you will become familiar

    reply
    0
  • Cancelreply