Array common methods

  1. push()To the arrayThe backInserts one or more elements and returns the resultThe length of the array. (Changes the original array)
  2. pop()Delete from arrayThe last element, returns the result isThe deleted element. (Changes the original array)
  3. unshift()In the arrayThe front ofInserts one or more elements and returns the resultThe new length of the array. (Changes the original array)
  4. shift()Delete from arrayThe first element, returns the result isThe deleted element. (Changes 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()From an array ofextractOne or more of the specified elements is returned asNew array. (Does not change the original array)
New array = original array. Slice (start index position, end index position); Before closed after openingCopy the code
			var arr = ["a"."b"."c"."d"."e"]
			
			var result1 = arr.slice(2);// Start with 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 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 the code

Slice () converts a pseudo-array to a true array:

array = Array.prototye.slice. Call (arrayLike) or array = []. Call (arrayLike) or array =Array.from(arrayLike)// New API in ES6
Copy the code
  1. splice()From an array ofdeleteOne or more of the specified elements is returned asNew array. (Changes the original array)
New array = old array.splice (start index index, number to delete, content added); Elements can be deleted or addedCopy the code
			var arr = ["a"."b"."c"."d"."e"]
			
			var result1 = arr.splice(1.0."boy");// Delete 0 content, add element from index 1
			var result2 = arr.splice(1.1);// Delete an element, return the value of the deleted element
			var result3 = arr.splice(1.2."skr");// Remove two elements and add a new one
			
			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 the code
  1. concat()Joins two or more arrays and returnsNew array. (Does not change the original array)
New array = old array. Concat (Array one, array two...)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 the code
  1. join()Converts an array to a string, returning the resultConverted string. (Does not change the original array)
New string = original array. Join (parameter);// Optional

Copy the code
     var arr = ["A"."B"."C"."D"];

      console.log(arr.toString()); //A,B,C,D
      var str1 = arr.join(); // Same as toSting() when no arguments are passed
      var str2 = arr.join("-"); // The argument passed in can be used as a string split symbol
      var str3 = arr.join(""); // Passing null does not require a split symbol

      console.log(str1); //A,B,C,D
      console.log(str2); //A-B-C-D
      console.log(str3); //ABCD

Copy the code

9. Reverse () reverses the array, and returns an array that is reversed. (Changes the original array)

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

Copy the code

10. Sort () sorts the elements of an array from smallest to largest in Unicode by default. (Changes the original array)

When sort() is used without arguments, it defaults to sorting from smallest to largest in Unicode encodingCopy the code
      var arr1 = ["2"."50"."100"."8"."44"]; // When the array is a string
      var newArr = arr1.sort(); // Compare to the Unicode encoding of the first value of the string
      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(); // The first value of the string is compared to the Unicode encoding
      console.log(newArr); //[12, 2, 30, 400, 56, 6]

Copy the code

If we take arguments in the sort() method, we can customize the sorting by adding a callback function that defines two arguments that the browser will call using elements from the array as arguments. Sort by return value:

  1. If a value greater than 0 is returned, the elements alternate positions
  2. If a value less than 0 is returned, the element position remains the same
  3. If 0 is returned, 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 the code

Array traversal

  1. forEach()No return value, similar to the 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 the 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 the code

2. Map () processes each item of the array to form a new array (without changing the original array)

      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

Copy the code

The 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
      // Map function principle
      arr.__proto__.forMap = function (fn) {
        var newArr = [];
        for (var i = 0; i < this.length; i++) {
          / / I: index values
          //this[i] = arr[i]
          //this:arr
          newArr.push(fn(this[i], i, arr));
        }
        return newArr; // Map has return values
      };
      var arr3 = arr.forMap(fn);
      console.log(arr3); / /,11,12,13,14,15 [10]

Copy the code

3. Filter () runs the callback function on each item in the array, and returns true to form a new array. (Does not change the original array).

      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 and 6)

Copy the 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);
      // Returns a new array, the filtered array
      console.log(arr2); / / / three, four, five
      // 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 values
          //this[i] = arr[i]
          //this:arr
          var isSava = callBack(this[i], i, this);
          / / isSave to a Boolean value
          if (isSava) {
            newArr.push(this[i]); }}return newArr;
      };
      var arr3 = arr.forMap(fn);
      console.log(arr3); / / / three, four, five

Copy the code

4. Stop every() if one of the items returns false, this method returns false.

            //every is used to determine whether all arrays meet the criteria
            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 the code
  1. some()If one of the entries returns true, the traversal is stopped, 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 are numbers less than 100.")}Copy the code
  1. reduce()Performs a callback function for each element in the array.

Reduce () requires traversal of the content and can be used to output a result

           var arr = [80.50.100.200.300];
			var sum =arr.reduce(function(value,item,index,arr){
				//value is the initial value. The current initial value is 0
				return value+item;
			},0)
			console.log(sum);/ / 730

Copy the code

Other methods of arrays

  1. Indexof () and lastIndexof ()

Indexof (value) : index from front to back to get the index value of the first occurrence of the element = array. LastIndexof (value) : Index back to the last occurrence of the index value of the element = array. These two methods can be used to determine whether there is a value in the element, if not, return -1.

           var arr = ["Cold"."Cruel"."Back to life"."Iron hand"];
			var result1 = arr.indexOf("Cruel");
			var result2 = arr.lastIndexOf("Iron hand");
			var result3 = arr.indexOf("Kris Wu");
			console.log(result1);/ / 1
			console.log(result2);/ / 3
			if(result3 == -1) {console.log("The data doesn't exist.")// Data does not exist
			}else{
				console.log("Data exists")}Copy the code

2. Find () finds the first element that meets [returns true for the specified condition]. Once the first element is found, no further traversal is performed.

               find(function(item,index,arr){
                     return true
               })

Copy the code
            var arr = [12.52.62.32.12];
			var result = arr.find(function(item,index){
				return item>30
			})
			console.log(result);/ / 52
Copy the code
  1. findIndex()Find the index value that meets the condition
var arr = [12.52.62.32.12];
			var result = arr.findIndex(function(item,index){
				return item>30
			})
			console.log(result);/ / 1
Copy the code
  1. Array.from()Traverses the pseudo-array through the real array

Array.prototype is not in the pseudo-array prototype chain, while array. prototype is in the real Array. 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);
Copy the code
  1. Array.of()Converts a series of values to an array
var arr = Array.of(value1,value2,.....)

            var Ary = Array.of(1."one"["Two"."three"])
			console.log(Ary)//[1, "one", Array(2)]
Copy the code