Home  >  Article  >  Web Front-end  >  JS implementation code for inserting characters into an array (please refer to JavaScript splice() method)_javascript skills

JS implementation code for inserting characters into an array (please refer to JavaScript splice() method)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:38:411248browse
Copy code The code is as follows:

Array.prototype.ArrayInsertAfter=function(Num,obj)
{
var tempArr=new Array();
var l=this.length;
for(var i=0;i{
tempArr.push(this .shift());
}
l=tempArr.length;
for(var i=0;i{
this.push(tempArr.shift( ));
if(i==Num)
{
this.push(obj);
}
}
return this;
}

JavaScript splice() method usage instructions
Definition and usage
The splice() method is used to insert, delete or replace elements of an array.

Syntax
arrayObject.splice(index,howmany,element1,...,elementX)
参数 描述
index

必需。规定从何处添加/删除元素。

该参数是开始插入和(或)删除的数组元素的下标,必须是数字。

howmany

必需。规定应该删除多少元素。必须是数字,但可以是 "0"。

如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。

element1 可选。规定要添加到数组的新元素。从 index 所指的下标处开始插入。
elementX 可选。可向数组添加若干元素。
Return value
If an element is deleted from arrayObject, the array containing the deleted element is returned.
Description
The splice() method can delete zero or more elements starting from index and replace those deleted elements with one or more values ​​declared in the parameter list .
Tips and Notes
Note: Please note that the splice() method has different functions from the slice() method. The splice() method will directly modify the array.
Example
Example 1
In this example, we will create a new array and add an element to it:

[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh to execute
]
Output:


George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
Example 2

In this example we will delete the element at index 2 and add a new element to replace the deleted element:

[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute
]
Output:

George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
Example 3
In this case Here we will delete the three elements starting from index 2 ("Thomas") and add a new element ("William") to replace the deleted element:
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute ]

Output: George,John,Thomas,James,Adrew,Martin George,John,William,Martin
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn