零零乙 2009-02-25 14:29 采纳率: 33.3%
浏览 348
已采纳

如何在特定索引处的数组中插入项?

I am looking for a Javascript array insert method, in the style of:

arr.insert(index, item)

Preferably in jQuery, but any Javascript implementation will do at this point.

转载于:https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index

  • 写回答

11条回答 默认 最新

  • ℡Wang Yan 2009-02-25 14:32
    关注

    What you want is the splice function on the native array object.

    arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

    In this example we will create an array and add an element to it into index 2:

    var arr = [];
    arr[0] = "Jani";
    arr[1] = "Hege";
    arr[2] = "Stale";
    arr[3] = "Kai Jim";
    arr[4] = "Borge";
    
    console.log(arr.join());
    arr.splice(2, 0, "Lene");
    console.log(arr.join());

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条