Array Replication
/* 1. How to copy an array? The simplest way is to loop through this array and add each item to the new array.
If someone gives you such a question, the answer should not be what the other party wants.
Array. Slice (START, [end])
The Slice Method returns an array object, which contains the specified part of arrayobj. (It can also be used for the string type)
Parameter Details,
Start (non-negative ).
End, optional. It is the length of an array or string. Positive integer, the length to be truncated; negative number. The length to be removed starts from the end of an array or string.
*/
Window. onload = function (){
VaR source = [4, 5, 6,"FF",NewDate ()];
VaR target = source. Slice (0,-3 );// Expected to remove the following three elements. Expected result: [4, 5]
VaR TARGET2 = source. Slice (0, 3 );// [4, 5, 6]
Log (target. Join (','); Log (target2.join (','));
Source ="Aabbccdd";
Target = source. Slice (0,-3 );// Remove the following three elements to obtain aabbc.
TARGET2 = source. Slice (0, 3 );// AAB
Log (target); log (TARGET2 );
}
Remove repeated array items
// Remove duplicate items. Two methods are provided here.
VaRArr = arr2 = [1, 2, 2, 3,"AA","AA","BB"];
VaRNewarr = [], tempobj = {};
For(VaRI = 0; I <arr. length; I ++ ){
If(Tempobj [arr [I])
Continue;
Newarr. Push (ARR [I]);
Tempobj [arr [I] = arr [I];
}
// Use a regular expression. replace all the current elements with the current element to ensure that the current element only appears once.
Newarr = arr. Join (',') +",";
For(VaRI = 0; I <arr2.length; I ++ ){
VaRReg =NewRegexp (arr2 [I] +",","G");
Newarr = newarr. Replace (Reg,"") + Arr2 [I] +",";
}
Log (newarr. Split (','))
Merge arrays (deduplication)
// Merge Arrays
VaRArr1 = [1, 2, 3];VaRArr2 = [3, 4, 5];
Newarr = arr1.join (',') +",";
For(VaRI = 0; I <arr2.length; I ++ ){
VaRReg =NewRegexp (arr2 [I] +",","G");
Newarr = newarr. Replace (Reg,"") + Arr2 [I] +",";
}
Log (newarr. Split (','))
Pseudo Array
Here, objects that meet the following conditions are called pseudo arrays.
1, with the Length attribute
2. Data Storage by index
3. methods such as push and pop with no Array
4. You can use array. Prototype. Slice to convert an object with the Length attribute to a real array.
VaREarr = {0:"", 1:"B", 2:"C", Length: 3 };
// Log (earr [1]); B
For(VaRI = 0; I <earr. length; I ++ ){
// Log (earr [I]); A B C
}
/* Earr is the same as a ['A', 'B', 'C'] array */
VaRToarray =Function(){
Return[]. Slice. Call (arguments );
}
Log (toarray (3, 5 ));// 3, 5
Log (toarray (3, 5). constructor); // Array
Common pseudo arrays include function arguments, childnodes, jquery, and so on.
// Convert the array into a pseudo Array
VaRArr = [1, 2, 3,""];
VaROBJ = {length: 0 };
[]. Push. Apply (OBJ, arr)
For(VaRIInOBJ ){
Log (I +""+ OBJ [I]);
}
Output: 0 1 1 2 2 3 3 a length 4
Convert a real array to a pseudo array:
[]. Push. Apply (this, []);