Comprehensive summary: What are the methods of arrays?

  1. unshift() - (at the beginning) add one or more elements to the array, returns the new array length, will change the length of the array

let arr=[0,1,2,3,4]
arr.unshift(2,99)
console.log(arr);//[2, 99, 0, 1, 2, 3, 4]
  1. push () - (at the end) add one or more elements to the array, return the new array length, will change the length of the array

let arr=[0,1,2,3,4]
arr.push(99)
console.log(arr);// [0, 1, 2, 3, 4, 99]
  1. shift()——Delete the first data of the array and return the length of the new array, which will change the original array. Does not accept parameters, and can only delete the first one of the array each time (writing parameters does not take effect)

let arr=[0,1,2,3,4]
arr.shift()
console.log(arr);// [1, 2, 3, 4]
  1. pop()——Delete the last bit of the array and return the deleted data, which will change the original array. No parameters are accepted, and only the last one can be deleted each time

let arr=[0,1,2,3,4]
arr.pop()
console.log(arr);// [0,1, 2, 3]
  1. splice (starting position, number of deletions/0 means adding, adding content) - delete the specified number of elements at the specified position and then add any number of elements (realize the addition, deletion, and modification of any position in the array), and return the deleted data, which will change the original array of , generating a new array

let arr=[0,1,2,3,4]
arr.splice(1,2,99)//在下标为1的位置删除两个并添加99进去
console.log(arr);// [0, 99, 3, 4]

arr.splice(1,0,99)//在下标为1的位置添加99进去
console.log(arr);// [0, 99, 1, 2, 3, 4]

How to convert an array to a string

  1. toString()——Convert the array to a string and return the converted new array without changing the original array

let arr=["a","b","c","d","e"]
let str=arr.toString()
console.log(str)//a,b,c,d,e
  1. join()——separator (default ","), splicing the array to form a string ("" is to separate everything) returns the new array after splicing, and does not change the original array

let arr=["a","b","c","d","e"]
let str=arr.join("-")//以join里面的格式进行拼接
console.log(str)//a-b-c-d-e

How to convert string to array

  1. split()——Split (default is the whole string), use the specified delimiter, split the string into an array, and return a new array without changing the original array

let str="ab&bcd&d"
let arr=str.split()
console.log(arr)//["ab&bcd&d"]

let arr=str.split("")
console.log(arr)// ["a", "b", "&", "b", "c", "d", "&", "d"]

let arr=str.split("&")
console.log(arr)//["ab", "bcd", "d"]

array lookup method

  1. indexof (the element to be searched, the starting position to be searched)——(If the second parameter is not written, the search starts from subscript 0 by default) Query the position where an element appears for the first time in the array, and return the following If it does not exist, it will return -1 (you can judge whether the element exists through the return value: disguised form)

对数组:
let arr=["a","b","c","a","d","i","a","d"]
let index=str.indexOf("i")//默认就是从下标0开始
console.log(index)//5

let index=str.indexOf("a",3)//从下标3开始进行查找
console.log(index)//3

也针对字符串:
let str="abc&audij-jlaccd"
let index=str.indexOf("u")//默认就是从下标0开始
console.log(index)//5

let index=str.indexOf("a",3)//从下标3开始进行查找
console.log(index)//4
  1. lastindexof (ele, startindex) —— query the last occurrence position of an element in the array (or understand it as reverse query the first occurrence position) If the element exists, return the subscript, if it does not exist, return -1 (you can By return value: judging whether the element exists in disguise)

对数组:
let arr=["a","b","c","a","d","i","a","d"]
let index=arr.lastIndexOf("a")
console.log(index)//6

let index=arr.lastIndexOf("d",3)//从下标为3的地方网下标为0的地方查找
console.log(index)//-1

也针对字符串:
let str="abc&audij-jlaccd"
let index=str.indexOf("a")//默认就是从最后的开始下标0进行数
console.log(index)//12

let index=str.indexOf("d",3)
console.log(index)//-1
  1. reverse()——Reverse the elements in the array, return the reversed array, and change the original array

let arr=["a","b","c","a","d","i","a","d"]
let revarr=arr.reverse()
console.log(revarr)//["d", "a", "i", "d", "a", "c", "b", "a"]
  1. sort (function (a, b) {return ab}) - sort the array in alphabetical order (string Unicode code points), return a new array, will change the original array (ab is from small to large, ba is from large to Small)

let arr=[1,6,0,5,8,4,2]
arr.sort(function(a,b){
        return a-b
})
console.log(arr)//[0, 1, 2, 4, 5, 6, 8]

let arr=[{name:"haha",age:12},{name:"momo",age:10},{name:"xixi",age:16}]
arr.sort(function(a,b){
     return a.age-b.age
})
console.log(arr)// [{name:"momo",age:10}, {name:"haha",age:12}, {name:"xixi",age:16}]
  1. concat()——connects multiple arrays, creates a new array by merging (connecting) existing arrays, returns the merged array, and does not change the original array

If the stitching is an array, expand the array, and then put each element in the array into a new array;

If it is another type, put it directly into the new array;

In addition, if no parameters are given to the method, an array that is the same as the original array (copy array) will be returned

let arr1=[1,2,3]
let arr2=["a","b","c"]
let arr3=[23,56,89]
let newarr=arr3.concat(arr2,arr1)
console.log(newarr)//[23, 56, 89, "a", "b", "c", 1, 2, 3]
  1. slice (startindex, endindex) - intercept the string, cut the array at the specified position, the new array formed by the cut elements will not change the original array

Parameter description: startIndex start subscript, default value 0

endIndex terminates the subscript default value length, can accept negative numbers, (counting backwards)

Notice! The interval between the start subscript and the end subscript is left-closed and right-open [ a , b) can get to the start, but not to the end

slice() If no parameters are passed, the default value will be used to get a new array with the same elements as the original array (copy the array)

let arr3=[23,56,89]
let newarr=arr3.slice(0,2)
console.log(newarr)//[23, 56]

ES5's new method of traversing arrays

  1. forEach()——(iteration) traverses the array, and executes the incoming callback function in each loop. (Note: forEach() will not execute the callback function for empty arrays.) There is no return value, or it is understood that the return value is undefined, and the original array will not be changed.

The biggest difference between forEach and map is: forEach has no return value and will not generate a new array, while map has a return value and will generate a new array

arr.forEach(function(item,index,arr){
//里面的function是一个回调函数,
//item: 数组中的每一项;
//index:item 对应的下标索引值
//arr: 就是调用该方法的数组本身
})
  1. map()——(iteration) traverses the array, executes the callback function passed in each cycle, and generates a new array according to the return value of the callback function, the same as the forEach() method, but the map() method has a return value, Can return out;

let arr = [1,32,54,6,543];
let res = arr.map(function(item,index,arr){
    return item*2;   //让每一个元素都乘2
})
console.log(res)// [2, 64, 108, 12, 1086]
  1. filter()——(iteration) traverses the array, executes the incoming callback function each time it loops, the callback function returns a condition, and filters out the elements that meet the condition and puts them in the new array to form a new array of elements that meet the condition

Parameters: item: the current element of each loop, index: the index of the current item, array: the original array;

var list = [32, 93, 77, 53, 38, 87];
var resList = list.filter(function (item, index, array) {
    return item >= 60; // true || false
});
console.log(resList);//[93, 77, 87]
  1. every()—— (iteration) Determine whether all the elements in the array meet a certain condition, all of which are satisfied and return true, as long as one of them is not satisfied, return false, and the original array will not be changed, which is equivalent to logical AND

var list = [32, 93, 77, 53, 38, 87];
var result = list.every(function (item, index, array) {
     return item >= 50;
});
 console.log(result);//false
  1. some()—— (iteration) to determine whether there is an element in the array, as long as there is one element that satisfies a certain condition, it will return true, and if it is not satisfied, it will return false, which is equivalent to logical or

var list = [32, 93, 77, 53, 38, 87];
var result = list.some(function (item, index, array) {
     return item >= 50;
});
 console.log(result);//true
  1. reduce()——traversing the array, executing the incoming callback function each time the loop is executed, the callback function will return a value, use this value as the initial value prev, pass it into the next function, and return the result of the final operation;

Syntax: arr.reduce(function(prev,item,index,array){})

Parameters: prev initial value (similar to sum = 0) You can set the initial value (parameter), if you do not set the initial value, the default is the first element in the array, and traverse from the second element when traversing

item the current element for each loop

index The current index of each loop

array original array

  1. Sum calculation
第一次:pre–>1     next–>2     index–>1
pre+next=1+2=3
第二次:pre–>3     next–>3     index–>2
pre+next=3+3=6
第三次:pre–>6     next–>4     index–>3
pre+next=6+4=10
第四次:pre–>10     next–>5     index–>4

var arr1 = [1,2,3,4,5] ;
var new1 = arr1.reduce(function(pre,next,index){
        return pre+next ;
       //pre+next=10+5=15
})
 console.log(new1);//15
  1. Flattening arrays (splicing arrays) - one reduce can only flatten one layer of arrays
var arr2 = [[1,2,3],[4,[5,9,10]],[6,7]] ;
var new2 = arr2.reduce(function(pre,next,index){
     console.log(pre);//[1, 2, 3]      [1, 2, 3, 4, Array(3):[5,9,10]]
     return pre.concat(next);    //前数组拼接后数组 .concat()
})
 console.log(new2);//[1, 2, 3, 4, [5,9,10], 6, 7]
  1. Object array overlay calculation
var arr3 = [{price:10,count:1},{price:15,count:2},{price:10,count:3}];
var new3 = arr3.reduce(function(pre,next,index){
            return pre+next.price*next.count;
 },0)    //在原数组第一项添加为0,不改变原数组,则可不操作第一项
console.log(new3);//70
  1. Application: counting the number of occurrences of each element in an array (eg: voting board)
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice','Bob', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
    // console.log(allNames, '|' + name);
   if (name in allNames) {
        allNames[name]++;
    } else {
         allNames[name] = 1;
    }
    return allNames;
}, {});//最先给定一个空数组
 console.log(countedNames);//{Alice: 3, Bob: 2, Tiff: 1, Bruce: 1}

Guess you like

Origin blog.csdn.net/qq_64180670/article/details/129483798