返回

从初学者到进阶,数组常用API手册速览

前端

数组常用API

1. push()方法

push()方法用于在数组的末尾添加一个或多个新的元素,并返回新数组的长度。

const numbers = [1, 2, 3];
numbers.push(4, 5); // [1, 2, 3, 4, 5]

2. pop()方法

pop()方法用于删除数组最后一个元素,并返回数组末尾的元素。

const numbers = [1, 2, 3, 4, 5];
numbers.pop(); // 5

3. unshift()方法

unshift()方法用于在数组前面添加一个或多个新的元素,并返回新数组的长度。

const numbers = [1, 2, 3];
numbers.unshift(0, -1); // [-1, 0, 1, 2, 3]

4. shift()方法

shift()方法用于删除数组第一个元素,并返回数组第一个元素。

const numbers = [1, 2, 3, 4, 5];
numbers.shift(); // 1

5. splice()方法

splice()方法用于添加、删除或替换数组中的元素,并返回一个包含被删除元素的新数组。

const numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 1); // [1, 2, 4, 5]
numbers.splice(2, 0, 3); // [1, 2, 3, 4, 5]
numbers.splice(2, 2, 6, 7); // [1, 2, 6, 7, 5]

6. slice()方法

slice()方法用于创建一个新的数组,该数组包含数组中指定范围的元素。

const numbers = [1, 2, 3, 4, 5];
numbers.slice(1, 3); // [2, 3]

7. concat()方法

concat()方法用于将两个或多个数组连接成一个新的数组。

const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
numbers1.concat(numbers2); // [1, 2, 3, 4, 5, 6]

8. join()方法

join()方法用于将数组中的所有元素连接成一个字符串,并返回该字符串。

const numbers = [1, 2, 3, 4, 5];
numbers.join(); // "1,2,3,4,5"

9. reverse()方法

reverse()方法用于反转数组中的元素,并返回该数组。

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

结语

数组是JavaScript中一种非常重要的数据结构,掌握数组的常用API可以帮助您高效管理数组数据,并编写出更加简洁高效的代码。