Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

javascript - 如何在特定索引(JavaScript)的数组中插入项目?(How to insert an item into an array at a specific index (JavaScript)?)

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

(我正在寻找一种JavaScript数组插入方法,其样式为:)

arr.insert(index, item)

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

(最好是在jQuery中,但此时任何JavaScript实现都可以。)

  ask by tags2k translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(您想要的是本机数组对象上的splice函数。)

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).

(将在指定索引处将item插入到arr中(首先删除0项目,也就是说,它只是一个插入)。)

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

(在此示例中,我们将创建一个数组并将一个元素添加到索引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()); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...