The native array splice Method for one JS demo every day. Key knowledge points: Train the logic of thinking, understand the array method, and consider various situations. js runs regularly on a daily basis.
<! DOCTYPE html>
<Html lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> Title </title>
</Head>
<Body>
<Script>
/*
* Splice (start, deleteCount, data1, data2, data3 ...)
**/
Var arr = ['A', 'B', 'C', 'D', 'E'];
// 1, 3
// [8, 6, 4]
// ['A', 8, 6, 4]
// Arr. splice (-5 );
// Console. log (arr );
Function arrSplice (data, start, deleteCount ){
// If start is not a number or cannot be converted to a number, start is 0 by default.
If (isNaN (start )){
Start = 0;
}
Start = Number (start );
// If start is a negative number
If (start <0 ){
Start = data. length + start;
}
If (start <0 ){
Start = 0;
}
// If deleteCount is not passed
If (deleteCount = undefined ){
DeleteCount = data. length-start;
}
/*
* 1. Prepare an empty array to store the final result.
* 2. Loop source array
* 1. Obtain the subscript in the current loop.
* 2. Compare the subscript with start.
* 1. If the current subscript is smaller than start, add the current array to the new array.
* 2. Otherwise
* 1. Whether New data exists
* 1. If new data exists, add the new data to the new array.
* 2. Otherwise, if deleteCount is greater than 0, ignore the data and perform the following operations on deleteCount --
* Otherwise, add the current data to the new array.
**/
Var newArr = [];
// Add data
Var newData = [];
If (arguments. length> 3 ){
For (var I = 3; I <arguments. length; I ++ ){
// NewData. push (arguments [I]);
NewData [newData. length] = arguments [I];
}
}
For (var I = 0; I <data. length; I ++ ){
If (I <start ){
// NewArr. push (data [I]);
NewArr [newArr. length] = data [I];
} Else {
If (newData. length ){
// New data
// NewArr = newArr. concat (newData );
For (var j = 0; j <newData. length; j ++ ){
NewArr [newArr. length] = newData [j];
}
NewData. length = 0;
}
If (deleteCount> 0 ){
DeleteCount --;
} Else {
// NewArr. push (data [I]);
NewArr [newArr. length] = data [I];
}
}
}
Data = newArr;
Console. log (data );
}
</Script>
</Body>
</Html>