Summary of 22 commonly used APIs for arrays in JS

I. Introduction

In front-end development, arrays are a common and important data structure. Arrays provide many convenient methods for manipulating and manipulating the data within them. This article will briefly introduce the commonly used APIs of arrays in the front end, including operations such as adding, deleting, intercepting, merging, and converting.

Two, push() method and pop() method

The push() method is used to add one or more elements to the end of the array and return the modified array 新长度.

const fruits = ['苹果', '香蕉'];
const res = fruits.push('橘子', '西瓜');
console.log(fruits);  //[ '苹果', '香蕉', '橘子', '西瓜' ]
console.log(res);     //4

The pop() method is used to remove and return the last element of the array.

const fruits = ['苹果', '香蕉', '橘子'];
const lastFruit = fruits.pop();
console.log(fruits);     // ['苹果', '香蕉']
console.log(lastFruit); //橘子

Three, shift() method and unshift() method

The shift() method is used to remove and return 第一个the elements of the array.

const fruits = ['苹果', '香蕉', '橘子'];
const firstFruit = fruits.shift();
console.log(fruits);      //[ '香蕉', '橘子' ]
console.log(firstFruit);  //苹果

The unshift() method is used to shift 开头添加one or more elements of an array and returns the new length of the modified array.

const fruits = ['苹果', '香蕉'];
const newLength = fruits.unshift('橘子', '西瓜');
console.log(fruits);        //[ '橘子', '西瓜', '苹果', '香蕉' ]
console.log(newLength); //4

4. slice() method

The slice() method is used to intercept the element at the specified position from the array and return a new array.

The syntax is: array.slice(start, end), where, startand endare optional parameters, indicating the starting and ending positions of the selected elements. If no parameters are passed in, the entire array is selected by default. This method returns a new array containing elements from startto end( ).不包括end

const names = ['张三', '李四', '王五', '赵六'];
const slicedNames = names.slice(1, 3);
const slicedNames1 = names.slice();
const slicedNames2 = names.slice(0);
const slicedNames3 = names.slice(2);
const slicedNames4 = names.slice(3);
const slicedNames5 = names.slice(4);

//slice不改变原数组
console.log(names);          //[ '张三', '李四', '王五', '赵六' ] 
console.log(slicedNames);  //[ '李四', '王五' ]
console.log(slicedNames1); //[ '张三', '李四', '王五', '赵六' ] 
console.log(slicedNames2); //[ '张三', '李四', '王五', '赵六' ] 
console.log(slicedNames3); //[ '王五', '赵六' ]
console.log(slicedNames4); //[ '赵六' ]
console.log(slicedNames5); //[] 参数大于等于4时就输出空数组

Five, splice () method

The splice() method is used to delete, replace or add elements from an array and return an array of the deleted elements, which directly modifies the original array.

grammar:array.splice(start, deleteCount, item1, item2, ...)

Among them, start indicates the starting position to be modified, deleteCount indicates the number of elements to be deleted, and item1, item2, etc. indicate the elements to be added. If deleteCount为0, it means that only elements are added and elements are not deleted.

//实现删除
let arr = [1,2,3,4,5]
console.log(arr.splice(0,2));  //[ 1, 2 ] 返回被删除的元素
console.log(arr);  //[ 3, 4, 5 ]   该方法会改变原数组

//实现添加
let arr2 = [1,2,3,4,5]
console.log(arr2.splice(1,0,666,777)); //[] 返回空数组,没有删除元素
console.log(arr2);  //[ 1, 666, 777, 2, 3, 4, 5 ]  原数组改变了

// 实现替换
let arr3 = [1,2,3,4,5]
console.log(arr3.splice(2,1,"aaa","bbb")); //[ 3 ]  返回被删除的一个元素
console.log(arr3);  //[ 1, 2, 'aaa', 'bbb', 4, 5 ]  可以添加字符串

let arr4 = [1,2,3,4,5]
console.log(arr4.splice(1,4,666)); //[ 2, 3, 4, 5 ]  返回被删除的四个元素
console.log(arr4);  //[ 1, 666 ]

6. join() method

The join() method is used to join all the elements in the array into one with the specified delimiter 字符串.

const fruits = ['苹果', '香蕉', '橘子'];
const joinedString = fruits.join(',');
console.log(fruits);  //[ '苹果', '香蕉', '橘子' ]
console.log(joinedString); //苹果,香蕉,橘子

Seven, concat () method

The concat() method is used to combine two or more arrays and return a new array.

const fruits1 = ['苹果', '橘子'];
const fruits2 = ['西瓜', '蓝莓'];
const combinedFruits = fruits1.concat(fruits2);
console.log(combinedFruits); //[ '苹果', '橘子', '西瓜', '蓝莓' ]

Eight, forEach () method

The forEach() method is used to execute a callback function for each element in the array.

const fruits = ['火龙果', '蓝莓', '西瓜', '葡萄'];
fruits.forEach(fruit => {
    
    
  console.log(fruit); //火龙果 蓝莓 西瓜 葡萄
});

Nine, map () method

The map() method is used to execute a callback function for each element in the array and return a new array, the elements in the new array are the return value of the callback function.

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); //[ 1, 4, 9, 16, 25 ]

10. filter() method

The filter() method is used to filter and filter the eligible elements in the array, and return a new array.

//筛选出偶数
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); //[ 2, 4 ]

Eleven, reduce () method

The reduce() method is a method of the array object, which is used to merge and calculate all the elements in the array according to the specified rules, and return a final value.

grammar:array.reduce(callback, initialValue)

This method receives two parameters, the first parameter is a callback function, and the second parameter is an initial value. The callback function can receive four parameters, namely:

  1. accumulator: The accumulator is used to store the return value or initial value of the last callback function.
  2. currentValue: The value of the current element.
  3. currentIndex: The index of the current element.
  4. array: the array object itself.

initialValue is the initial value, an optional parameter.

const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((acc, num) => {
    
    
  return acc + num
}, 10);
console.log(sum); //25
//如果初始值是设为0,则输出15

12. fill() method

The fill method in JS can fill all elements in an array, and it will directly modify the original array.

grammar:array.fill(value, start, end)

Among them, value represents the value to be filled, and start and end represent the start position and end position to be filled. If start and end are not passed in, the entire array will be filled by default. This method returns the modified original array.

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

//将数组中从位置2到位置4(不包括位置4)的元素都填充为6
arr.fill(6, 2, 4);
console.log(arr);  //[ 0, 0, 6, 6, 0 ]

13. Array lookup API

1. includes () method

The includes method is used to check whether an element is contained in the array, and return true if it is included, otherwise return false.

Unlike the indexOf() method, the includes() method does not support specifying a starting position, it searches from the beginning of the array.

const fruits = ['苹果', '香蕉', '橘子', '西瓜', 1, 2, 3];
console.log(fruits.includes('橘子')); //true
console.log(fruits.includes('葡萄')); //false
console.log(fruits.includes(3));      //true
console.log(fruits.includes(4));      //false

2. indexOf () method

Note that the indexOf method will only return the position of the first match. If there are multiple identical elements in the array, this method will only return the position of the first element.

In addition, the indexOf method can also accept an optional second parameter, which is used to specify where to start searching.

const fruits = ['苹果', '蓝莓', '橘子', '西瓜', '葡萄'];
console.log(fruits.indexOf('橘子', 1));  //2  返回元素下标
console.log(fruits.indexOf('橘子', 3));  //-1  没有该元素
const arr = [1,2,3,4,5,6,7,6,6,5];
// 从下标6开始查找元素5
console.log(arr.indexOf(5,6)); //9

3.lastIndexOf()() method

The lastIndexOf() method is used to find the index (position) of the last occurrence of an element in the array, and return the index value if found, otherwise return -1.

const fruits = ['火龙果', '橘子', '蓝莓', '西瓜', '葡萄', '橘子'];
console.log(fruits.lastIndexOf('橘子')); //5
console.log(fruits.lastIndexOf('柚子')); //-1

4. findIndex() method

The findIndex() method is used to find the index of the element that satisfies the condition in the array, and returns the index value if found, otherwise returns -1.

const arr = [1, 2, 3, 4, 5, 6];
const index = arr.findIndex(num => num > 3);
console.log(index);   //3  返回第一个符合条件的元素的下标
const index2 = arr.findIndex(num => num > 10);
console.log(index2); //-1  不存在符合条件的元素

14. sort() method

The sort() method is used to sort the array in-place, which directly modifies the original array without creating a new one. By default, it treats array elements as strings and sorts them by Unicode code point. However, custom comparison functions can be passed in to implement sorting based on other rules.

比较函数: The comparison function receives two parameters, usually referred to as a and b, representing the two elements to be compared. It should return a negative, zero, or positive number indicating whether a should come before b, at the same position as b, or after b. The return value rules of comparison functions are as follows:

  1. If the return value is less than 0, a is sorted before b.
  2. If the return value is equal to 0, the relative positions of a and b remain unchanged.
  3. If the return value is greater than 0, a is sorted after b.
const arr = [3, 1, 5, 2, 4];
arr.sort();
console.log(arr);  //[1, 2, 3, 4, 5]

//默认排序(按照 Unicode 码点排序)
const arr = ['f', 'k', 'c', 'a', 'b'];
arr.sort();
console.log(arr);  //[ 'a', 'b', 'c', 'f', 'k' ]

//使用比较函数进行自定义排序
const arr = [10, 2, 66, 26, 13, 1];
arr.sort((a, b) => a - b);
console.log(arr);  //[ 1, 2, 10, 13, 26, 66 ]

const arr = [10, 2, 66, 26, 13, 1];
arr.sort((a, b) => b - a);
console.log(arr);  //[ 66, 26, 13, 10, 2, 1 ]

15. The reverse() method

The reverse() method is used to reverse the order of elements in the array, that is, to arrange the elements of the array in reverse order.

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

Sixteen, toString () and toLocaleString () method

The toString method converts the array to a string consisting of the array elements separated by commas.

const arr = [1, 2, 3, 4, 5];
console.log(arr.toString());  //1,2,3,4,5
const arr2 = ['苹果', '蓝莓', '橘子', '西瓜', '葡萄'];
const arr3 = ['a', 'null', 'b', 'c', 'undefined', 'd', 'e']
console.log(arr2.toString());  //苹果,蓝莓,橘子,西瓜,葡萄
console.log(arr3.toString());  //a,null,b,c,undefined,d,e

The toLocaleString method converts the array into a string composed of array elements, and the elements are also separated by commas, but it will determine the format of the elements according to the language and regional settings of the current environment.

//根据当前环境的语言和地区设置来决定元素的格式
const arr = [123456.789, new Date()];
//我补充写作的时间
console.log(arr.toLocaleString()); //123,456.789,2023/5/29 07:57:19

const arr2 = [1000, 2000, 3000];
const str = arr2.toLocaleString();
console.log(str); //1,000,2,000,3,000

17. Array.from() method

Array.from() is a 类数组或可迭代对象static method in JavaScript for creating a new array from. It takes an iterable or array-like object and returns a new array instance.

Array.from(iterable, mapFn, thisArg)

  1. iterable: required, an iterable or array-like object used to create new arrays.
  2. mapFn (optional): A mapping function that processes each element and returns an element in a new array.
  3. thisArg (optional): Optional parameter, this value when executing the mapFn function.
//使用字符串创建数组
const str = "Hello";
const arr = Array.from(str);
console.log(arr); //[ 'H', 'e', 'l', 'l', 'o' ]
//使用类似数组的对象创建数组
const obj = {
    
    
  0: "榴莲",
  1: "牛油果",
  2: "蓝莓",
  length: 3
};
const arr = Array.from(obj);
console.log(arr);  //[ '榴莲', '牛油果', '蓝莓' ]
//使用映射函数处理数组元素
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = Array.from(numbers, num => num * 2);
console.log(doubledNumbers); //[ 2, 4, 6, 8, 10 ]

Eighteen, the last words

This article introduces the commonly used APIs for arrays in the front end, covering common operations such as adding, deleting, intercepting, merging, and converting. Proficiency in these methods can improve a certain development efficiency. In actual development, please select the appropriate array method according to your specific needs.

Guess you like

Origin blog.csdn.net/weixin_45506717/article/details/131430983