Common methods of arrays in JavaScript & array traversal

Common methods of arrays in JavaScript & array traversal

1. Array common methods

  1. push()
    The array rearmost insertion of one or more elements, returns a value of the length of the array . (Will change the original array)
  2. pop()
    Delete the last element in the array, and return the result as the deleted element . (Will change the original array)
  3. unshift()
    In an array of front insertion of one or more elements, it returns a value of the new length of the array . (Will change the original array)
  4. shift()
    Delete the first element in the array, and return the result as the deleted element . (Will change the original array)
var arr = [ "a" , "b" , "c" , "d" , "e" ] var arrPush = arr.push( "ok" ) console .log(arrPush); //6 var arrPop = arr. pop( "ok" ); console .log(arrPop); //ok var arrUnshift = arr.unshift( " skr " , "ok" ) console .log(arrUnshift); //7 var arrShift = arr.shift() ; Console .log (arrShift); //SKR copy the code
  1. slice()
    Extract the specified one or more elements from the array, and return the result as a new array . (Will not change the original array)
= New array .slice original array (index start position, end position index); front opening and closing duplicated code
var arr = [ "a" , "b" , "c" , "d" , "e" ] var result1 = arr.slice( 2 ); //Extract from the second value var result2 = arr.slice(- 2 ); //Extract the last two elements var result3 = arr.slice( 1 , 3 ); //Extract the index from the first to the fourth value (but not including the fourth) var result4 = arr.slice( 4 , 0 ); //empty console .log(result1); //["c", "d", "e"] console .log(result2); //["d", "e"] console .log(result3); //["b", "c"] console .log(result4) ; //[] Copy code

slice() can convert a pseudo array to a true array:

array = Array .prototye.slice.call(arrayLike) or array = [].call(arrayLike) or = Array the Array .from (arrayLike) //the new API for ES6 copy the code
  1. splice()
    Delete the specified one or more elements from the array, and return the result as a new array . (Will change the original array)
Original new array = array .splice (starting index index, the number you want to delete, add contents); you can also add an element remove an element copy the code
var arr = [ "a" , "b" , "c" , "d" , "e" ] var result1 = arr.splice( 1 , 0 , "boy" ); //Delete 0 content, add element from index value 1 var result2 = arr.splice( 1 , 1 ); //Delete an element, return Deleted element value var result3 = arr.splice( 1 , 2 , "skr" ); //Delete two elements and add new elements console .log(arr); //["a", "boy", "b", "c", "d", "e"] console .log(result1); //[] console .log(result2 ); //["boy"] console .log(result3); //["b", "c"] console .log(arr); //["a", "skr", "d", " e"] Copy code
  1. concat()
    Connect two or more arrays, and return the result as a new array . (Will not change the original array)
Array = new original array .concat (a arrays, two arrays, ...) copy the code
var arr1 = [ 1 , 2 , 3 ]; var arr2 = [ "a" , "b" , "c" ]; var arr3 = [ "one" , "two" , "three" ]; var newArr1 = arr1.concat(arr2); var newArr2 = arr1.concat(arr2, arr3); console .log(newArr1); //[1, 2, 3, "a", "b", "c"] console .log(newArr2); //[1, 2, 3, "a", "b ", "c", "one", "two", "three"] Copy code
  1. join()
    Convert the array to a string, and return the result as the converted string . (Will not change the original array)
New string = original array.join(parameter); //parameter optional Copy code
var arr = [ "A" , "B" , "C" , "D" ]; console .log(arr.toString()); //A,B,C,D var str1 = arr.join(); //The usage is the same as toSting() when no parameters are passed var str2 = arr.join( "- " ); //The passed-in parameter can be used as the segmentation symbol of the string var str3 = arr.join( "" ); // If the input is empty, the segmentation symbol is not required console .log(str1); //A,B,C,D console .log(str2); //ABCD console .log(str3); //ABCD Copy code

9.

reverse()
Reverse the array, and return the result as the reversed array . (Will change the original array)

The reversed array = array.reverse(); Copy code
var arr = [ "A" , "B" , "C" , "D" ]; var arrReverse = arr.reverse(); console .log(arrReverse); //["D", "C", "B", "A"] Copy code

10.

sort()
The elements of the array are sorted according to the Unicode encoding by default , from small to large. (Will change the original array)

When using sort() without parameters, it will be sorted according to Unicode encoding by default, from small to large Copy code
var arr1 = [ "2" , "50" , "100" , "8" , "44" ]; //When the array is a string var newArr = arr1.sort(); //According to the first string Compare the Unicode encoding of the values console .log(newArr); //["100", "2", "44", "50", "8"] var arr2 = [ 2 , 56 , 400 , 12 , 30 , 6 ]; //When the array is a string var newArr = arr2.sort(); //It is also compared according to the Unicode encoding of the first value of the string console .log(newArr); //[12, 2, 30, 400, 56, 6] Copy code

If you include parameters in the sort() method, we can customize the sorting rules, add a callback function, define two parameters in the callback function, and the browser will use the elements in the array as actual parameters to call the callback function. According to the return value to determine the sort:

  1. If a value greater than 0 is returned, the elements will alternate positions
  2. If a value less than 0 is returned, the element position is unchanged
  3. If it returns 0, the two elements are equal, and the positions are not swapped
var arr3 = [ 45 , 88 , 11 , 66 , 100 ]; var newArr1 = arr3.sort(); //[100, 11, 45, 66, 88] console .log(newArr1); var fn = function ( a , b ) { if (a> b) { return 1 ; } else { return - 1 ; } }; var newArr2 = arr3.sort(fn); console .log(newArr2); //[11, 45, 66, 88, 100] Copy code

2. Array traversal

  1. forEach()
    No return value, similar to for loop
var hotModel = yidianzu.data.hotModel; console .log(hotModel); for ( var i = 0 ; i <hotModel.length; i++) { console .log(i); console .log(hotModel[i]); } var fn = function ( item, index, arr ) { //item:hotModel[i] index:i arr:hotModel console .log(item); console .log(index); }; hotModel.forEach(fn); Copy code

Function principle:

var fn = function ( item, index, arr ) { //item:hotModel[i] index:i arr:hotModel console .log(item); console .log(index); }; hotModel.forEach(fn); //forEach function principle hotModel.__proto__.forEvery = function ( fn ) { for ( var i = 0 ; i < this .length; i++) { //this refers to hotModel fn( this [i], i, this ) ; } }; hotModel.forEvery(fn); Copy code

2.

map()
Process each item of the array and compose the array into a new array (the original array will not be changed)

var arr = [ 1 , 2 , 3 , 4 , 5 ]; var fn = function ( item, index ) { return item + 10 ; }; var arr2 = arr.map(fn); console .log(arr2); //[10,11,12,13,14,15] returns a new array, which is the array after map modification Copy code

Function principle

var arr = [ 1 , 2 , 3 , 4 , 5 ]; var fn = function ( item, index ) { return item + 10 ; }; var arr2 = arr.map(fn); console .log(arr2); //[10,11,12,13,14,15] returns a new array, which is the modified array of map//The principle of map function arr .__proto__.forMap = function ( fn ) { var newArr = []; for ( var i = 0 ; i < this .length; i++) { //i:index value //this[i] = arr[i] //this:arr newArr.push(fn( this [i], i, arr)); } return newArr; //map has a return value }; var arr3 = arr.forMap(fn); console .log(arr3); //[10,11,12,13,14,15] Copy code

3.

filter()
Run the callback function for each item in the array, and change the item whose return result is true will form a new array , and the returned result will be a new array, playing a filtering role. (The original array will not be changed).

var arr = [ 1 , 2 , 3 , 4 , 5 , 6 ]; var arr2 = arr.filter( function ( item, index ) { if (item> 3 ) { return true ; } else { return false ; } }); console .log(arr2); //[4,5,6] Copy code

Function principle:

var arr = [ 1 , 2 , 3 , 4 , 5 ]; var fn = function ( item, index, arr ) { if (item> 2 ) { return true ; } else { return false ; } }; var arr2 = arr.filter(fn); //return a new array, which is the filtered array console .log(arr2); //[3,4,5] //map function principle arr.__proto__.forMap = function ( callBack ) { var newArr = []; for ( var i = 0 ; i < this .length; i++) { //this refers to the current array arr-->arr.forMap(fn) //i: Index value //this[i] = arr[i] //this:arr var isSava = callBack( this [i], i, this ); //isSave is a boolean value if (isSava) { newArr.push( this [i]); } } return newArr; }; var arr3 = arr.forMap(fn); console .log(arr3); //[3,4,5] Copy code

4.

every()
If one item returns false, stop traversal, and this method returns false.

//every is used to judge whether the array meets all conditions var arr = [ 80 , 50 , 100 , 200 , 300 ]; var isArr = arr.every( function ( item,index,arr ) { if (item> 100 ){ return true ; } else { return false } }) if (isArr){ console .log( "All numbers are greater than 100" ) } else { console .log( "There are numbers less than 100" ) //There are numbers less than 100 } Copy code
  1. some()
    If one item returns true, stop traversal and this method returns true.
var arr = [ 80 , 50 , 100 , 200 , 300 ]; var isArr = arr.some( function ( item,index,arr ) { if (item> 100 ){ return true ; } else { return false } }) if (isArr){ console .log( "At least one number is greater than 100" ) //At least one number is greater than 100 } else { console .log( "There is a number less than 100" ) } Copy code
  1. reduce()
    Execute the callback function for each element in the array.

reduce() needs to traverse the content, and you can use reduce() when you finally output a result

var arr = [ 80 , 50 , 100 , 200 , 300 ]; var sum = arr.reduce( function ( value,item,index,arr ) { //value is the initial value and the current initial value is 0 return value+item; }, 0 ) console .log(sum); //730 Copy code

Three. Other methods of array

  1. indexof() and lastIndexof()

indexof(value) : Get the index value of the first occurrence of the element from the front-to-back index = array. indexof(value); lastIndexof(value) : Get the index value of the index of the last occurrence of the element from the front-to-back index= Array.lastIndexof(value); Use these two methods to determine whether there is a value in the element, and return -1 if it does not exist.

var arr = [ "cold-blooded" , "ruthless" , "following" , "iron hand" ]; var result1 = arr.indexOf( "ruthless" ); var result2 = arr.lastIndexOf( "iron hand" ); var result3 = arr.indexOf( "Wu Yifan" ); console .log(result1); //1 console .log(result2); //3 if (result3 ==- 1 ){ console .log( "Data does not exist" ) //Data does not exist } else { console .log( "data exists" ) } Copy code

2.

find()
Find the first element that satisfies the [specified condition returns true]. Once the first element that meets the condition is found, it will not continue to traverse down.

find( function ( item,index,arr ) { return true }) Copy code
var arr = [ 12 , 52 , 62 , 32 , 12 ]; var result = arr.find( function ( item,index ) { return item> 30 }) Console .log (Result); //52 is duplicated code
  1. findIndex()
    Find the index value that satisfies the condition
var arr = [ 12 , 52 , 62 , 32 , 12 ]; var result = arr.findIndex( function ( item,index ) { return item> 30 }) console .log(result); // 1Copy code
  1. Array.from()
    Traverse the pseudo array into a true array

There is no Array.prototype in the pseudo-array prototype chain, while the true array contains Array.prototype. So there are no array-related methods in pseudo-arrays.

var fn = function () { console .log( arguments ) var arr = Array .from( arguments ); console .log(arr); //[1,2,3] } Fn ( . 1 , 2 , . 3 ); duplicated code
  1. Array.of()
    Convert a series of values to an array
var arr = Array .of(value1,value2,.....) var Ary = the Array .of ( . 1 , "One" , [ "Two" , "Three" ]) Console .log (Ary) //[. 1, "One", the Array (2)] Copy Code