如何在一个特定的索引中插入项目到一个数组? [英] How to insert an item into an array at a specific index?

查看:177
本文介绍了如何在一个特定的索引中插入项目到一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个Javascript数组插入方法,风格:

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

arr.insert(index, item)

preferably jQuery的,但任何Javascript实现将做到这一点。

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

推荐答案

你想要的是在 <一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice\"><$c$c>splice本机数组对象的功能。

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

arr.splice(索引,0,项目); 将插入项目 ARR 的指定索引处。

arr.splice(index, 0, item); will insert item into arr at the specified index.

在这个例子中,我们将创建一个数组和一个元素添加到入索引2:

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());

在code的输出将是:

The output of the code above will be:

Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Lene,Stale,Kai Jim,Borge

这篇关于如何在一个特定的索引中插入项目到一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆