JavaScript common array methods - summary

quick search 

method analysis

1:concat();

Function: 合并数组, one or more arrays can be merged, and the data after the merged arrays will be returned, 不会改变原来的数组;

var str1 = [12,2,"hello"];var str2 = ["world"];
console.log(str1.concat(str2));        //[12, 2, "hello", "world"]
console.log(str1);                //[12,2,"hello"];

2:join();

Function: Convert an array to a string and return the converted string data without changing the original array;

Note: Use double quotes in () to include the delimiter you want to use. The default is a comma. It is convenient to observe here. I used -  

var str1 = [12,2,"hello"];
var str2 = ["world"];
console.log(str1.join("-"));        //12-2-hello
console.log(str1);              //[12, 2, "hello"]

3:pop();

function: 删除数组的最后一位, and返回删除的数据,会改变原来的数组

var str1 = [12,2,"hello"];
console.log(str1.pop()        //hello
console.log(str1);          //[12, 2]

4:shift();

Function: 删除数组的第一位数据, and 返回删除的数据,会改变原来的数组.

5:unshift();

function: in the array 首位新增一个或多数据, and返回新数组的长度,会改变原来的数组

Note: unshift()The data returned by the method is the length of the new array, and the data it adds can be one or more, which can be understood as adding a series of data,

var str1 = [12,2,"hello"];
var str2 = [43,2,"test"];
console.log(str1.unshift("你好"));              //4
console.log(str2.unshift("hello","world"));        //5
console.log(str1);                       //["你好", 12, 2, "hello"]
console.log(str2);                       //["hello", "world", 43, 2, "test"]

6:push();

Function: Add one or more data to the last digit of the array, and return the length of the new array, which will change the original array

Note: The data returned by the push() method is the length of the new array. The data it adds can be one or more, which can be understood as adding a series of data.

var str1 = [12,2,"hello"];
var str2 = [43,2,"test"];
console.log(str1.push("你好"));          //4
console.log(str2.push("hello","world"));    //5
console.log(str1);                 //[12, 2, "hello","你好"]
console.log(str2);                 //[43, 2, "test","hello", "world"]

7:reverse();

Function: will数组的数据进行反转,并且返回反转后的数组,会改变原数组

var str1 = [12,2,"hello"];
console.log(str1.reverse());      //["hello", 2, 12]
console.log(str1);            //["hello", 2, 12]

8:sort();

Function: Sort the data in the array (the default is ascending order), and return the sorted new array, which will change the original array

Notice:

  • 8.1: The sorting here is 针对字符的排序to use the array toString()method to convert it into a string first, and then compare it bit by bit, 3 is greater than 12, because the first bit 3>1, do not confuse it with Numberthe type data sorting
  • 8.2: str2Three characters are added to the array. You can see that when comparing, zoomit is the largest, because the first English letter ASCIIcan be converted into the corresponding value through the code, and then compare according to the value
var str1 = [12,2,43,5,2,5];
var str2 = [92,2,43,"hello",'zoom',5,2,5];
console.log(str1.sort());//[12, 2, 2, 43, 5, 5]
console.log(str1);//[12, 2, 2, 43, 5, 5]
console.log(str2.sort());//[2, 2, 43, 5, 5, 92, "abc", "hello", "zoom"]
console.log(str2);//[2, 2, 43, 5, 5, 92, "abc", "hello", "zoom"]
  • 8.3: Sorting Problems

Parameters: sort(callback) If you need to sort by value, you need to pass parameters. sort(callback), callbackis the callback function that should take two parameters, compare the two parameters, and return a number describing the relative order of the two values (a-b). Its return value is as follows:

Returns a value less than 0 if a is less than b.

Returns 0 if a is equal to b.

Returns a value greater than 0 if a is greater than b.

var str3 = [92,2,43,5,2,5];     
console.log(str3.sort(fn));                 //[2, 2, 5, 5, 43, 92]
console.log(str3);                      //[2, 2, 5, 5, 43, 92]
function fn (a,b){
    return a-b;
 }

9:slice();

Function: Intercept the array at the specified position and return the intercepted array without changing the original array

parameter:slice(startIndex, endIndex)

Note: Selected elements can be returned from an existing array. This method accepts two parameters slice(start,end), stsrtwhich are mandatory, indicating the starting position; endoptional, indicating the ending position (not including the end position), and omitting it means the last position; both start and end can be negative numbers, When the number is negative, it means counting from the last digit, such as -1 means the last digit.

var arr = ["T1","J1","L1","L2","M1"];
    console.log(arr.slice(1,3));        //["J1","L1"]
    console.log(arr.slice(1));          //["J1","L1","L2","M1"]
    console.log(arr.slice(-4,-1));      //["J1","L1","L2"]
    console.log(arr.slice(-2));         //["Lily","M1"]
    console.log(arr.slice(1,-2));       //["J1","L1"]
    console.log(arr);                   //["T1","J1","L1","L2","M1"]

10:splice();

Function: Add to the array, or delete from the array, or replace the elements in the array, and then return the deleted/replaced element.

Parameters: splice(start,num,data1,data2,...); All parameters are optional.

var arr = ["Tom","Jack","Lucy","Lily","May"];
console.log(arr.splice(2,0,"a","b"));//[]
console.log(arr);//["Tom", "Jack", "a", "b", "Lucy", "Lily", "May"]---原数组改变

11:toString();

Function: convert array to string, 类似于没有参数的join(). This method will be automatically called when the data undergoes implicit type conversion. If it is called manually, it will be directly converted to a string. does not change the original array

var str = [1,2,3];
console.log(str.toString()); //1,2,3
console.log(str);//[1,2,3]

12:valueOf();

Function: Return the original value of the array (in general, it is actually the array itself), which is usually called by js in the background and does not appear explicitly in the code

var str = [1,2,3];
console.log(str.valueOf()); //[1,2,3]
console.log(str); //[1,2,3]
//为了证明返回的是数组自身
console.log(str.valueOf() == str);//true

13:IndexOf();

Function: According to the specified data, from left to right, query the position in the array, if the specified data does not exist, return -1, if the specified data is found, return the index of the data

Parameters: indexOf(value, start); value is the data to be queried; start is optional, indicating the starting position of the query. When start is negative, it counts forward from the end of the array; if the value cannot be found, then method returns -1

注意:如果找到该数据,立即返回该数据的索引,不再往后继续查找

var str = ["h","e","l","l","o"];
 console.log(str.indexOf("l"));        //2
 console.log(str.indexOf("l",3));      //3
 console.log(str.indexOf("l",4));      //-1
 console.log(str.indexOf("l",-1));     //-1
 console.log(str.indexOf("l",-3));     //2

14:lastIndexOf();

Function: The lastIndexOf() method can return the last occurrence position of a specified string value, if the second parameter start is specified, then 在一个字符串中的指定位置从后向前搜索.

Parameters: lastIndexOf(value, start); value is the data to be queried; start is an optional integer parameter. Specifies the position in the string to start searching. Its valid values ​​are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the last character of the string.

var str = ["h","e","l","l","o"];
console.log(str.lastIndexOf("l"));        //3
console.log(str.lastIndexOf("l",3));      //3
console.log(str.lastIndexOf("l",4));      //3
console.log(str.lastIndexOf("l",-1));     //3
console.log(str.lastIndexOf("l",-3));     //2
  • Note: This method 从后向前retrieves the string, but returns the position of the last occurrence of the substring counting from the start position (0). to see if it contains a string. The search starts at the start of the string or the end of the string (when start is not specified). 如果没有找到匹配字符串则返回 -1 。
  • Note: the lastIndexOf() method is case sensitive!

15:forEach();

Function: ES5 new method, used to traverse the array, no return value,

Parameters: forEach(callback); callback has three parameters by default, which are value (the data of the traversed array), index (the corresponding index), and self (the array itself).

var arr = ["Tom","Jack","Lucy","Lily","May"];
var a = arr.forEach(function(value,index,self){
     console.log(value + "--" + index + "--" + (arr === self));
})
// 打印结果为:
// Tom--0--true
// Jack--1--true
// Lucy--2--true
// Lily--3--true
// May--4--true
console.log(a);     //undefined---forEach没有返回值
//该方法为遍历方法,不会修改原数组

16:map();

Function:

Same as forEach function;

The callback function of map will return the execution result, and finally map will return the return values ​​of all callback functions into a new array.

  • Parameters: map(callback);callback has three parameters by default, respectively value,index,self. Same as the parameter of forEach() above
//功能1:同forEach
    var arr = ["Tom","Jack","Lucy","Lily","May"];
    var a = arr.map(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr === self))
    })
    // 打印结果为:
    // Tom--0--true
    // Jack--1--true
    // Lucy--2--true
    // Lily--3--true
    // May--4--true

    //功能2:每次回调函数的返回值被map组成新数组返回
    var arr = ["Tom","Jack","Lucy","Lily","May"];
    var a = arr.map(function(value,index,self){
        return "hi:"+value;
    })
    console.log(a);     //["hi:Tom", "hi:Jack", "hi:Lucy", "hi:Lily", "hi:May"]
    console.log(arr);   //["Tom", "Jack", "Lucy", "Lily", "May"]---原数组未改变

17:filter();

Functions: 1. Same as forEach function; 2. filter的回调函数需要返回布尔值,当为true时,将本次数组的数据返回给filter,最后filter将所有回调函数的返回值组成新数组返回(此功能可理解为“过滤”).

Parameters: filter(callback); callback has three parameters by default, which are value, index and self.

//功能1:同forEach
    var arr = ["Tom","Jack","Lucy","Lily","May"];
    var a = arr.filter(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr === self))
    })
    // 打印结果为:
    // Tom--0--true
    // Jack--1--true
    // Lucy--2--true
    // Lily--3--true
    // May--4--true

    //功能2:当回调函数的返回值为true时,本次的数组值返回给filter,被filter组成新数组返回
    var arr = ["Tom","Jack","Lucy","Lily","May"];
    var a = arr.filter(function(value,index,self){
        return value.length > 3;
    })
    console.log(a);         //["Jack", "Lucy", "Lily"]
    console.log(arr);       //["Tom", "Jack", "Lucy", "Lily", "May"]---原数组未改变

18:every();

Features: 判断数组中每一项是否都满足条件,只有所有项都满足条件,才会返回true.

Parameters: every() receives a callback function as a parameter. This callback function needs to have a return value, every(callback); callback has three parameters by default, which are value, index, and self.

Function 1: When the return value of the callback function is true, it is similar to the function of forEach, traversing all; if it is false, then stop the execution, and the subsequent data will not be traversed, 停在第一个返回false的位置.

//demo1:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.every(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
    })
    // 打印结果为:
    // Tom--0--true
    //因为回调函数中没有return true,默认返回undefined,等同于返回false

    //demo2:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.every(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
        return value.length < 4;
    })
    // 打印结果为:
    // Tom--0--true
    // abc--1--true
    // Jack--2--true
    //因为当遍历到Jack时,回调函数到return返回false,此时Jack已经遍历,但是后面数据就不再被遍历了

    //demo3:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.every(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
        return true;
    })
    // 打印结果为:
    // Tom--0--true
    // abc--1--true
    // Jack--2--true
    // Lucy--3--true
    // Lily--4--true
    // May--5--true
    //因为每个回调函数的返回值都是true,那么会遍历数组所有数据,等同于forEach功能

Function 2: When the return value of each callback function is true, the return value of every is true, as long as there is a callback function with a return value of false, the return value of every is false

19:some();

Features: 判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true.

Parameters: some() receives a callback function as a parameter. This callback function needs to have a return value, some(callback); callback has three parameters by default, which are value, index, and self.

Function 1: Because it is necessary to judge each item in the array, as long as there is a callback function that returns true, some will return true, so it is just the opposite of every. When a callback function returns true, the result can be determined, then Stop execution, the subsequent data will no longer be traversed, stop at the first position that returns true; when the return value of the callback function is false, it needs to continue to execute backwards, and the result can only be determined at the end, so all data will be traversed to achieve similar In the function of forEach, traverse all.

//demo1:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.some(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
        return value.length > 3;
    })
    // 打印结果为:
    // Tom--0--true
    // abc--1--true
    // Jack--2--true

    //demo2:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.some(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
        return true;
    })
    // 打印结果为:
    // Tom--0--true

    //demo3:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.some(function(value,index,self){
        console.log(value + "--" + index + "--" + (arr == self))
        return false;
    })
    // 打印结果为:
    // Tom--0--true
    // abc--1--true
    // Jack--2--true
    // Lucy--3--true
    // Lily--4--true
    // May--5--true

Function 2: Contrary to every, as long as there is a callback function whose return value is true, the return value of some is true, and the return value of all callback functions is false, and the return value of some is false

//demo1:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.some(function(value,index,self){
        return value.length > 3;
    })
    console.log(a);             //true

    //demo2:
    var arr = ["Tom","abc","Jack","Lucy","Lily","May"];
    var a = arr.some(function(value,index,self){
        return value.length > 4;
    })
    console.log(a);             //false

20.reduce();

Function: Start from the first item of the array, traverse to the end one by one, iterate all items of the array, and then 构建一个最终返回的值.

Parameters: reduce() receives one or two parameters: the first one is a callback function, indicating the function to be called on each item of the array; the second parameter (optional) is used as the initial value of the merge, and is called by the callback function The first parameter received at one execution time. reduce(callback, initial); callback has four parameters by default, which are prev, now, index, self. Any value returned by callback will be used as the first parameter of the next execution. If the initial parameter is omitted, then the first iteration occurs on the second item of the array, so the first parameter of callback is the first item of the array, and the second parameter is the second item of the array.

//demo1:不省略initial参数,回调函数没有返回值
    var arr = [10,20,30,40,50];
    arr.reduce(function(prev,now,index,self){
        console.log(prev + "--" + now + "--" + index + "--" + (arr == self))
    }, 2019)
    // 打印结果为:
    // 2019--10--0--true
    // undefined--20--1--true
    // undefined--30--2--true
    // undefined--40--3--true
    // undefined--50--4--true
    // 此时回调函数没有return,所以从第二次开始,prev拿到的是undefined

    //demo2:省略initial参数,回调函数没有返回值
    var arr = [10,20,30,40,50];
    arr.reduce(function(prev,now,index,self){
        console.log(prev + "--" + now + "--" + index + "--" + (arr == self))
    })
    // 打印结果为:第一次,回调函数的第一个参数是数组的第一项。第二个参数就是数组的第二项
    // 10--20--1--true
    // undefined--30--2--true
    // undefined--40--3--true
    // undefined--50--4--true
    // 此时回调函数没有return,所以从第二次开始,prev拿到的是undefined

    //demo3:不省略initial参数,回调函数有返回值
    var arr = [10,20,30,40,50];
    arr.reduce(function(prev,now,index,self){
        console.log(prev + "--" + now + "--" + index + "--" + (arr == self));
        return "hello";
    }, 2019)
    // 打印结果为:
    // 2019--10--0--true
    // hello--20--1--true
    // hello--30--2--true
    // hello--40--3--true
    // hello--50--4--true
    // 此时回调函数有return,所以从第二次开始,prev拿到的是回调函数return的值

    //demo4:省略initial参数,回调函数有返回值
    var arr = [10,20,30,40,50];
    arr.reduce(function(prev,now,index,self){
        console.log(prev + "--" + now + "--" + index + "--" + (arr == self));
        return "hello";
    })
    // 打印结果为:第一次,回调函数的第一个参数是数组的第一项。第二个参数就是数组的第二项
    // 10--20--1--true
    // hello--30--2--true
    // hello--40--3--true
    // hello--50--4--true
    // 此时回调函数有return,所以从第二次开始,prev拿到的是回调函数return的值

    //demo5:使用reduce计算数组中所有数据的和
    var arr = [10,20,30,40,50];
    var sum = arr.reduce(function(prev,now,index,self){
        return prev + now;
    })
    console.log(sum);      //150
    // 回调函数的最后一次return的结果被返回到reduce方法的身上

    //demo6:使用reduce计算数组中所有数据的和
    var arr = [10,20,30,40,50];
    var sum = arr.reduce(function(prev,now,index,self){
        return prev + now;
    }, 8)
    console.log(sum);      //158
    // 回调函数的最后一次return的结果被返回到reduce方法的身上
    // 因为reduce有第二个参数initial,在第一次执行时被计算,所以最终结果被加上8

21.reduceRight()

Function: (Similar to reduce) From 最后一项the beginning of the array, traverse forward one by one to the first position, iterate all items of the array, and then construct a final returned value.

Parameters: Same as reduce. demo: Same as reduce

Which array methods will change the original array

unshift();

push();

shift();

pop();

sort();

reverse();

splice();

These seven array methods have been introduced above. It can be seen that when these methods are used again, the original array will be changed.

Guess you like

Origin blog.csdn.net/JackieDYH/article/details/124491492