JS Array method

Source: Internet
Author: User

instanceof

Detects if an object is an array; (used to deal with complex data types;)
Simple data type typeof;
A instanceof b//A is not made of B;
Cases:
var arr = [n/a];
Console.log (arr instanceof Array); The arr genus is not of type array;

Array.isarray ()

Array.isarray (parameter); Determines whether the parameter is an array, returns a Boolean value;
Cases:
var arr = [n/a];
var num = 123;
Console.log (Array.isarray (arr)); True
Console.log (Array.isarray (num)); False

ToString ()

Array. toString (); Turns the array into a string, removes the [], and the contents are linked by commas;
Cases:
var arr = ["AAA", "BBB", "CCC"];
Console.log (Arr.tostring ()); Back to AAA,BBB,CCC

ValueOf ()

Array. valueOf (); Returns the array itself;
Cases:
var arr = ["AAA", "BBB", "CCC"];
Console.log (Arr.valueof ()); Returns the array itself ["AAA", "BBB", "CCC"]

Array. Join (parameter)

Array. Join (parameter); The elements in the array can be linked by parameters into a string;
Console.log (Arr.join ()); As with ToString (), use a comma link
Console.log (Arr.join ("|")); Link with parameters
Console.log (Arr.join ("&")); Link with parameters
Console.log (Arr.join ("")); If it's a space, it's really linked with a space.
Console.log (Arr.join ("")); Null characters are seamlessly connected

Adding and removing of array elements push () and pop ()

1. Array. push ()//Add elements at the very end of the array;
2. Array. Pop ()//no parameters required; Delete an item at the very end of the array;
Cases:
var arr = [n/a];
var AAA = Arr.push ("abc");//Add an element at the very end of the array;
Console.log (arr);//The element has been modified
Console.log (AAA);//The return value is the length of the array;

AAA = Arr.pop ();//no parameters required; Delete an item at the very end of the array;
Console.log (arr);//The element has been modified
Console.log (AAA);//The item that was deleted

Unshift () and Shift ()

1. Array. Unshift ()//Add an element to the front of the array;
2. Array. Shift ()//no parameters required; Delete one item at the top of the array;
Cases:
var arr = [n/a];
AAA = Arr.unshift ("abc");//Add an element to the front of the array;
Console.log (arr);//The element has been modified
Console.log (AAA);//The return value is the length of the array;

AAA = Arr.shift ();//no parameters required; Delete one item at the top of the array;
Console.log (arr);//The element has been modified
Console.log (AAA);//The item that was deleted

Array element sort reverse ()

Reverse ()//Flip Array
Cases:
var arr1 = [1,2,3,4,5];
var AAA = Arr1.reverse (); [5,4,3,2,1]

Sort ()

Sort ()//array of elements sorted; (default: Small to Large)
Default: Sort by the Unicode encoding of the first character; if the first one is the same then the second one is compared ...
Cases:
var arr = [4,5,1,3,2,7,6];
var aaa =arr.sort ();
Console.log (AAA); [1, 2, 3, 4, 5, 6, 7]
Console.log (AAA = = = arr);//True The original array is sorted (bubbling sort)
The alphabet can also be arranged by default;
var arr2 = ["C", "E", "D", "a", "B"];
var bbb = Arr2.sort ();
Console.log (BBB); ["A", "B", "C", "D", "E"]
Console.log (BBB===ARR2); True the original array is sorted (bubbling sort)

Sort ()//numeric size sorting method, need to use callback function;
Cases:
var arr = [4,5,1,13,2,7,6];
The return value inside the callback function is: Parameter 1-parameter 2; ascending; parameter 2-parameter 1; power-down;
Arr.sort (function (b) {
return a-B; Ascending
return b-a; Descending
return b.value-a.value; Sort by the size of the element's Value property;
});
Console.log (arr); [1, 2, 4, 5, 6, 7, 13]

Sort () Underlying principle

var AAA = Bubblesort ([1,12,3], function (A, b) {
Return a-b;//argument: array[j]-array[j+1];
Return b-a;//argument: array[j+1]-array[j];
});
Console.log (AAA);

function Bubblesort (ARRAY,FN) {
The number of Outer loop control wheel, the number of internal cycle control, are the number of elements-1;
for (Var i=0;i<array.length-1;i++) {
for (Var j=0;j<array.length-1-i;j++) {//times optimized, compare one round, less once;
Meet the conditional Exchange position;
if (Array[j]>array[j+1]) {//greater than ascending sort;
A-b>0 and a>b are a meaning;
B-a>0 and a<b are a meaning;
if (array[j]-array[j+1]>0) {//ascending sort
if (array[j+1]-array[j]>0) {//Power down sort
The two variables are sent to a function;
if (FN (array[j],array[j+1]) >0) {
var temp = array[j];
ARRAY[J] = array[j+1];
ARRAY[J+1] = temp;
}
}
}
Returns an array
return array;
}

Operation of the array element concat ()

Array 1.concat (array 2); Link two arrays;
var = [arr1];
var arr2 = ["A", "B", "C"];
var arr3 = Arr1.concat (ARR2);
Console.log (ARR3)//[1, 2, 3, "A", "B", "C"]

Slice ()

Array. Slice (start index value, end index value); Array interception;
Cases:
var arr = [1, 2, 3, "A", "B", "C"];
Console.log (Arr.slice (3)); From the index value of 3 truncated to the last; ["A", "B", "C"]
Console.log (Arr.slice (0,3)); Package left without packet right; [1, 2, 3]
Console.log (Arr.slice (-2)); The negative number is the latter; ["B", "C"]
Console.log (Arr.slice (3,0)); If the front is larger than the back, then it is []; []
Console.log (arr); The original array is not modified; [1, 2, 3, "A", "B", "C"]

Splice ()

Array. Splice (start index value, delete several, replace content 1, replace content 2, ...); replacement and deletion;
Change the original array; The return value is the deleted/replaced content
Cases:
var arr = [1,2,3,4,5,6, "A", "B", "C"]
Arr.splice (5); Intercept from index value 3 to last; (delete)
Console.log (arr); [1, 2, 3, 4, 5]
(Arr.splice); (delete specified number) Delete 2 from the beginning of index 1
Console.log (arr); [1, 4, 5]

Replace
var arr = [1,2,3,4,5,6, "A", "B", "C"];
Console.log (Arr.splice (3,3, "AAA", "BBB", "CCC")); (delete specified number and replace)
Console.log (arr); [1, 2, 3, "AAA", "BBB", "CCC", "a", "B", "C"]
Add to
Arr.splice (3,0, "AAA", "BBB", "CCC");//(delete specified number)
//
Console.log (arr);//intercept or replace; [1, 2, 3, "AAA", "BBB", "CCC", "AAA", "BBB", "CCC", "a", "B", "C"]

Indexof/lastindexof

Array. indexOf (Element); Give the element, check the index (formerly)
Array. lastIndexOf (Element); Give the element, look up the index (from back to forward)
Cases:
var arr = ["A", "B", "C", "D", "C", "B", "B"];
Console.log (Arr.indexof ("B")); 1 to return immediately after the search.
Console.log (Arr.lastindexof ("B")); 6 return immediately after finding
Console.log (arr.indexof ("xxx")); -1; If you can't find it, return-1;

Array iteration (traversal) every ()

Every item in an array runs a callback function, and if all returns True,every returns True,
If there is an item that returns false, the stop traversal every returns false;
Like a bodyguard blunder once, the game is over!!!
Cases:
1. var arr = [111,222,333,444,555];
Arr.every (function (a,b,c) {
Console.log (a); Elements
Console.log (b); Index value
Console.log (c); The array itself;
Console.log ("-----"); The array itself;
The elements in the array are assigned: c[b] = value; A= sometimes unable to assign value;
return true;
});

2.//every returns a bool value, all true is true; one is false and the result is false
var bool = arr.every (function (element, index, array) {
Judgment: We define that all elements are greater than 200;
if (element > 100) {
if (element > 200) {
return true;
}else{
return false;
}
})
alert (bool); False

Filter ()

Every item in an array runs a callback function that returns a new array of items that result in true
The new array is made up of elements in an old array, and return is an item of ture;
Cases:
var arr = [111,222,333,444,555];
var newArr = arr.filter (function (element, index, array) {
As long as it is an odd number, make an array; (distinguish elements in an array)
if (element%2 = = = 0) {
return true;
}else{
return false;
}
})

Console.log (NEWARR); [222, 444]

ForEach ()

As with a For loop; no return value;
Cases:
var arr = [111,222,333,444,555];
var sum = 0;
var AAA = Arr.foreach (function (Element,index,array) {
Console.log (Element); Each element in the output array
Console.log (index); The index value corresponding to the array element
Console.log (array); Array itself [111, 222, 333, 444, 555]
sum + = element; Sums the elements in an array;
});
Console.log (sum); Array elements add up to and
Console.log (AAA);//undefined no return value so return undefined

Map ()

Each item in an array runs a callback function that returns a new array that consists of the result of the function
Return what is in the new array; Do not return to undefined; Two-time array processing
Cases:
var arr = [111,222,333,444,555];
var newArr = Arr.map (function (element, index, array) {
if (index = = 2) {
return element; Return here so the value returned below is 333.
}
return element*100; The returned element value is multiplied by the value of 100.
})
Console.log (NEWARR); [11100, 22200, 333, 44400, 55500]

Some ()

The callback function is run for each item in the array, and if the function returns true for an item, some returns true; Like a killer, have a success, on the victory!!!
Cases:
var arr = [111,222,333,444,555];
var bool = arr.some (function (Ele,i,array) {
Judgment: There are multiples of 3 in the array
if (ele%3 = = 0) {
return true;
}
return false;
})
alert (bool); true; One success is true

Array empty

1. arr.length = 0; (Bad, pseudo-array cannot be emptied)
2. Arr.splice (0); Pseudo-arrays do not have this method;
3. arr = []; Can manipulate pseudo-arrays; (Recommended!)

Array case

1. Output a string array to the form of a | split, such as "Liu Bei | Zhang Fei | guan Yu". It is implemented in two different ways

var arr = ["Liu Bei", "Zhang Fei", "Guan Yu"];
var separator = "|";
Accumulate with a For loop
var str = arr[0];
for (Var i=1;i<arr.length;i++) {
str + = Separator+arr[i];
}
Console.log (str); Liu Bei | Zhang Fei | guan Yu
Join () links the elements in the array to strings;
Console.log (Arr.join ("|")); Liu Bei | Zhang Fei | guan Yu

2. Reverses the order of the elements of a string array. ["A", "B", "C", "D"], "D", "C", "B", "a"]. It is implemented in two ways. Hint: The first and length-i-1 are exchanged

Array. Reverse () method
var arr = ["A", "B", "C", "D"];
Console.log (Arr.reverse ()); ["D", "C", "B", "a"]

Three kinds: 1. Forward traversal, reverse add; 2. Reverse traversal, positive add; 3. Meta-array element exchange location;
for (Var i=0;i<arr.length/2;i++) {
var temp = arr[i];
Arr[i] = arr[arr.length-1-i];
Arr[arr.length-1-i] = temp;
}
Console.log (arr);

3. Array of Wages [1500, 1200, 2000, 2100, 1800], the deletion of wages over 2000

var arr = [1500, 1200, 2000, 2100, 1800];
Use filter () to form an array; return true; an array of components;
var newArr = arr.filter (function (ele, I, array) {
More than 2000 returns false;
if (ele<2000) {
return true;
}else{
return false;
}
});
Console.log (NEWARR); [1500, 1200, 1800]

4.["C", "a", "Z", "a", "X", "a"] find the position of each a in the array

var arr = ["C", "a", "Z", "a", "X", "a"];
Traversal Array (for/while/do...while) ForEach ();
Arr.foreach (function (ele, index, array) {
If the element equals "a", then the index value is output;
if ("a" = = = Ele) {
Console.log (index);
}
});

5. Write a method to remove duplicate elements of an array (array deduplication)

var arr = ["Naruto", "Naruto", "assistant", "adjuvant", "Sakura", "Sakura");
Method 1: The idea: Define a new array, traverse the old array, and judge if there is no old array of elements in the new array to add, otherwise do not add;
var newArr = [];
Traversing an old array
Arr.foreach (function (Ele,index,array) {
Detects elements in an old array that are not added if the new array exists, and does not exist;
if (Newarr.indexof (ele) = = = 1) {//does not exist to add; (To find the index value of an element in a new array, if 1 is not)
Newarr.push (ele);
}
});
Console.log (NEWARR); ["Naruto", "adjuvant", "Sakura"]

Original: 1190000012276002

JS Array method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.