【JavaScript】Array method summary (updated to ES7~)

1. Array.push()

Adds one or more elements to the end of the array and returns the new array length.The original array changes. Parameters can be added from one to many.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=fruits.push("Kiwi");
console.log(fruits)//(5) ["Banana", "Orange", "Apple", "Mango", "Kiwi"]    
console.log(x)//5  x是 新的数组长度
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=fruits.push("Kiwi","Java");
console.log(fruits) //(6) ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Java"]  
console.log(x)   // 6 x是 新的数组长度

2. Array.unshift()

to the arraybeginningAdd toone or moreelement, and returns the new array length.The original array changes

let arr = [1, 2, 3, 4, 5]
let res = arr.unshift(6, 7)
console.log(arr) //[6, 7, 1, 2, 3, 4, 5]
console.log(res) //7

3. Array.pop()

Removes and returns the last element of the array, or returns if the array is empty undefined.The original array changes

pop()method removes the last element from the array.

pop() 方法The return value of is the deleted item.

let arr = [1, 2, 3, 4, 5]
let res = arr.pop()
console.log(arr) //[1, 2, 3, 4]
console.log(arr.length) //4
console.log(res) // 5

4. Array.shift()

Removes the first item of the array and returns the value of the first element. Returns if the array is empty undefined.The original array changes

let arr = [1, 2, 3, 4, 5]
let res = arr.shift()
console.log(arr) //[2, 3, 4, 5]
console.log(arr.length) //4
console.log(res) // 1

5. Array.find()、findIndex()、findLast()、findLastIndex()

find()The method returns the value of the first element of the array that passes the test (judged within the function).

find()The method calls the function execution once for each element in the array:

When the elements in the array are returned when the condition is tested true, find()the element that meets the condition is returned, and the execution function will not be called for the subsequent value. Returns if there is no matching elementundefined

Note: find()For empty arrays, the function will not be executed.

Note: find()The original value of the array is not changed.

var ages = [3, 10, 18, 20];
 
function checkAdult(age) {
    
    
    return age >= 18;
}
 
console.log(ages.find(checkAdult)); // 18
console.log(ages); //  [3, 10, 18, 20]
[1, 4, -5, 10].find((n) => n < 0)
// -5

[1, 5, 10, 15].find(function(value, index, arr) {
    
    
  return value > 9;
}) // 10

findIndex(): Very similar to the find() method, returns the position of the first eligible array member, or -1 if all members do not meet the criteria.

[1, 5, 10, 15].findIndex(function(value, index, arr) {
    
    
  return value > 9;
}) // 2

Both methods can accept a second parameter, which is used to bind the this object of the callback function.

// find()函数接收了第二个参数person对象,回调函数中的this对象指向person对象。
function f(v){
    
    
  return v > this.age;
}
let person = {
    
    name: 'John', age: 20};
[10, 12, 26, 15].find(f, person);    // 26

find()and findIndex()both are checked backwards from the 0th bit of the array. ES2022 adds two new methods findLast()and findLastIndex(), starting from the last member of the array, check forward in turn, and keep everything else the same.

const array = [
  {
    
     value: 1 },
  {
    
     value: 2 },
  {
    
     value: 3 },
  {
    
     value: 4 }
];

array.findLast(n => n.value % 2 === 1); // { value: 3 }
array.findLastIndex(n => n.value % 2 === 1); // 2

6 .Array.concat(arr1,arr2…)

merge two or more arrays,generate a new arrayThe original array remains unchanged.

let arr1 = [1, 2, 3]
let arr2 = [4, 5]
let arr = arr1.concat(arr2)
console.log(arr)//[1, 2, 3, 4, 5]

7. Array.join()

Concatenate each item of the array with the specified characters to form a string. The default connection character is "," comma.

let arr = [1, 2, 3, 4, 5];
let str1 = arr.join('*')
let str2 = arr.join('-')
let str3 = arr.join('#')
console.log(str1)  // 1*2*3*4*5
console.log(str2)  // 1-2-3-4-5
console.log(str3)  // 1#2#3#4#5

8. Array.reverse()

Reverse the array.The original array changes

let arr=[1,2,3,4,5];
let newArr=arr. reverse();
console.log(newArr,arr) //newArr=[5,4,3,2,1]; arr=[5,4,3,2,1];

9. Array.sort()

Sort the array elements. Sort by string UniCode,The original array changes

default:

let arr=[2,3,5,1,4];

let newArr=arr.sort();
console.log(newArr,arr)//newArr=[1,2,3,4,5]; arr =[1,2,3,4,5]

Sort according to function rules:

①From childhood to adulthood

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    
    
  return a - b;
});
console.log(numbers);

②From big to small

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    
    
  return b - a;
});
console.log(numbers);  // [5, 4, 3, 2, 1]

③Sort according to a value in the array object

var arr = [
    {
    
    name:'zopp',age:0},
    {
    
    name:'gpp',age:18},
    {
    
    name:'yjj',age:8}
];

function compare(property){
    
    
    return function(a,b){
    
    
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
console.log(arr.sort(compare('age')))

// 打印结果:按照age排序

(3) [{
    
    }, {
    
    }, {
    
    }]
0: {
    
    name: "zopp", age: 0}
1: {
    
    name: "yjj", age: 8}
2: {
    
    name: "gpp", age: 18}
length: 3
__proto__: Array(0)

10. Array.map(function())

After each item of the original array executes the function, a new array is returned. The original array remains unchanged. (Note the difference between this method and forEach).

var arr = ['a','b','c','d'];
arr.map(function(item,index,arr){
    
       //参数含义同forEach
       console.log(item);
       console.log(index);
   });
	3 a
	4 0
	3 b
	4 1
	3 c
	4 2
	3 d
	4 3

maporEachdifference from f

mapThe method returns a new array, and the elements in the array are the processed values ​​of the original array elements after calling the function.

forEachThe method return value is always undefined. (It can also be said that there is no return value)

11. Array.slice(start,end)

Starts from start, ends before end, and does not reach end;
if no end value is given, it starts from start to the end of the array. start can be given a negative value, -1 means the last position of the array, -2 means the penultimate one, and so on, regardless of the past.

When there is only one value, delete from the current position to the end of the array

Intercept the content of the specified location of the copied array

slice (start position, end position); the second parameter is not written to the end by default, it can only be intercepted from front to back; the returned value is a new array formed by the intercepted content;

let arr=[1,2,3,4,5]
let copyArr=arr.slice(); // slice()或者slice(0)都可以复制数组;
let newArr=arr.slice(1,3);//截取索引1到索引3(不包括3)的值;
console.log(newArr,arr,copyArr)//newArr=[2,3];arr=[1,2,3,4,5];

12. Array.splice(index,howmany,arr1,arr2…)

index required. Integer specifying where to add/remove items, use negative values ​​to specify the position from the end of the array.
howmanyoptional. The number of items to delete. If set to 0, no items will be removed.
arr1, …, arr2optional. The new item to add to the array.
Delete elements and add elements, indexdelete howmanyelements starting from position, and insert arr1、arr2…data indexsequentially from position. howmanyWhen 0, the element is not deleted. The original array changes.

let arr = [1,2,3,4,5];
let num1 = arr.splice(1);
console.log(num1,arr) //num1=[2,3,4,5];arr=[1];

When there are two values, the first value is the location of deletion, and the second value is the number of deletions;

let arr=[1,2,3,4,5]
let num1=arr.splice(2,3)//删除从索引值2开始的3个元素
console.log(num1,arr);// num1=[3,4,5],arr=[1,2]

When there are three or more values, the first value is the position of the inserted element, the second value is the number of replacements, and the following values ​​are all new elements inserted;

let arr=[1,2,3,4,5]
let num2=arr.splice(2,1,6,7,8);//从索引值2开始替换掉1个元素,并且插入6,7,8

//如果第二个值为0,则不替换,直接插入6,7,8;
console.log(num2,arr);//被替换的值num2=[3]; arr=[1,2,6,7,8,4,5]

13. Array.forEach(function())

Called for each element of the array, passing the element to the callback function. The original array remains unchanged. (Note the difference between this method and map, if you print Array.forEach directly, the result is undefined).

var arr = [1, 3, 5, 13, 2];
var res = arr.forEach(function(item,index) {
    
    
    console.log(`数组第${
      
      index+1}个元素是${
      
      item}`);
 })
    console.log(res);//forEach的返回值为undefined,
// 数组第1个元素是1
// 数组第2个元素是3
// 数组第3个元素是5
// 数组第4个元素是13
// 数组第5个元素是2

14. Array.filter(function)

Filter the elements in the array that meet the criteria and return a new array.

var ages = [32, 33, 16, 40];

function checkAdult(age) {
    
    
    return age >= 18;
}
console.log(ages.filter(checkAdult))
VM57:6 (3) [32, 33, 40]

single-argument single-row arrow function

As shown in the following code snippet, it is very simple:

const fn= foo =>`${
      
      foo} world`;

This is the most compact form of an arrow function and is often used for simple processing functions such as filtering. As shown in the following code snippet:

let array=['a','bc','def','ghij'];
array=array.filter(item=>item.length>=2);

15. Array.every(function())

Judge each item in the array, and return if they match true, otherwise return false.

every()The method is used to check whether all elements of the array meet the specified conditions (provided by the function).

every()method checks all elements in the array using the specified function:

If an element in the array is detected to be unsatisfactory, the entire expression returns false, and the remaining elements are not checked.

Returns true if all elements satisfy the condition.

Note: every()There is no check for empty arrays.

NOTE: every()The original array will not be changed.

var ages = [32, 33, 16, 40];

function checkAdult(age) {
    
    
    return age >= 18;
}
console.log(ages.every(checkAdult)) // false

16. Array.some(function())

Judge each item in the array, and return if none match false, otherwise return true.

some()The method is used to check whether the elements in the array meet the specified conditions (provided by the function).

some()The method executes each element of the array in turn:

If one element satisfies the condition, the expression returns true, and the remaining elements are not checked.
Returns if no element satisfies the condition false.

Note: some()There is no check for empty arrays.

NOTE: some()The original array will not be changed.

var ages = [3, 10, 18, 20];

function checkAdult(age) {
    
    
    return age >= 18;
}
console.log(ages.some(checkAdult))  // true

Array.everyand Array.somethe difference

method difference

every(): Each item returns true to return true

some(): Return true as long as one item returns true

17. Array.reduce(function())

reduce()The method receives a function as an accumulator, and each value in the array (from left to right) is initially reduced and finally calculated as a value.

let arr = [1, 2, 3, 4, 5]
const add = (a, b) => a + b
let sum = arr.reduce(add)
console.log(sum) // 4 15

18. Array.isArray()

isArray()method is used to determine whether an object is an array.

Return if the object is an array true, otherwise return false.

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
console.log(Array.isArray(fruits)) // true

19. Array.forEach()

var arr = [1, 3, 5, 13, 2];
var res = arr.forEach(function(item,index) {
    
    
console.log(`数组第${
      
      index+1}个元素是${
      
      item}`);
    })
console.log(res);//forEach的返回值为undefined,
// 数组第1个元素是1
// 数组第2个元素是3
// 数组第3个元素是5
// 数组第4个元素是13
// 数组第5个元素是2
// undefined //敲黑板——forEach()是没有返回值的!

20. Array.toString()

This method converts an array to a string:

let arr = [1, 2, 3, 4, 5];
let str = arr.toString()
console.log(arr)   // [1, 2, 3, 4, 5]
console.log(str)  // 1,2,3,4,5

21. Array.from()

Array.from()The method is used to convert two types of objects into real arrays: array-like objects and iterable objects (including ES6's new data structures Setand Map).

Similar to an array: there is only one essential feature, that is, it must have a length attribute, so any object with a length attribute can be converted into an array through the Array.from() method.

let arrayLike = {
    
    
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5 的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

In general practical applications, common array-like objects are the NodeList collection returned by DOM operations, and the arguments object inside the function.

As long as the data structure of the Iterator interface is deployed, Array.from() can convert it into an array.

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

Array.from() can also accept a function as the second parameter, which is similar to the map() method of the array, which is used to process each element and put the processed value into the returned array.

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]

22. flat()、flatMap() 扁平化

flat()
Array.prototype.flat()It is used to "flatten" the nested array into a one-dimensional array. This method returns a new array and has no effect on the original data.

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]

flat()By default, only one layer will be "flattened". If you want to "flatten" a multi-layer nested array, you can write the flat()parameter of the method as an integer, indicating the number of layers you want to flatten. The default value is 1.

[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

If you want to convert it into a one-dimensional array no matter how many layers of nesting there are, you can use the Infinity keyword as a parameter.

[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

If the original array has space, the flat() method will skip the space.

[1, 2, , 4, 5].flat()
// [1, 2, 4, 5]

flatMap()
flatMap()It is equivalent to Map()+flat()executing each value first map, and then finally the wholeflat

flatMap()The method executes a function on each member of the original array (equivalent to executing Array.prototype.map()), and then executes the flat() method on the array of return values. This method returns a new array without changing the original array.

// 相当于 [[2, 4], [3, 6], [4, 8]].flat()
[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

flatMap()Only one level of array can be expanded.

// 相当于 [[[2]], [[4]], [[6]], [[8]]].flat()
[1, 2, 3, 4].flatMap(x => [[x * 2]])
// [[2], [4], [6], [8]]

flatMap()The parameter of the method is a traversal function, which can accept three parameters, which are the current array member, the position of the current array member (starting from zero), and the original array.

arr.flatMap(function callback(currentValue[, index[, array]]) {
    
    
  // ...
}[, thisArg])

flatMap()The method can also have a second parameter, which is used to bind this in the traversal function.

23. toReversed(),toSorted(),toSpliced(),with()

The traditional method of the general array will change the original array, such as, push()、pop()、shift()、unshift()etc., so there is a method that allows the operation of the array without changing the original array, and returns a copy of the original array.

  • Array.prototype.toReversed() -> Array
  • Array.prototype.toSorted(compareFn) -> Array
  • Array.prototype.toSpliced(start, deleteCount, ...items) -> Array
  • Array.prototype.with(index, value) -> Array

They respectively correspond to the original method of the array.

  • toReversed()Corresponding reverse(), used to reverse the position of the array members.
  • toSorted()Corresponding sort(), used to sort the array members.
  • toSpliced()Corresponding splice(), used to delete the specified number of members and insert new members at the specified position.
  • with(index,value)Corresponding splice(index, 1, value), used to replace the member at the specified position with a new value.

The above are the original methods corresponding to these four new methods. The meaning and usage are exactly the same. The only difference is that the original array will not be changed, but the copy of the original array will be returned.

const arr= [1, 2, 3];
arr.toReversed() // [3, 2, 1]
arr// [1, 2, 3]

const arr1= [3, 1, 2];
arr1.toSorted() // [1, 2, 3]
arr1// [3, 1, 2]

const array = [1, 2, 3, 4];
array.toSpliced(1, 2, 5, 6, 7) // [1, 5, 6, 7, 4]
array // [1, 2, 3, 4]

const arr2= [1, 1, 3];
arr2.with(1, 2) // [1, 2, 3]
arr2// [1, 1, 3]

Guess you like

Origin blog.csdn.net/Bon_nenul/article/details/128216658