一、引言
在前端开发中,数组是一种常见且重要的数据结构。数组提供了许多便捷的方法来操作和处理其中的数据。本文将简单介绍前端中数组常用的API,包括添加、删除、截取、合并、转换等操作。
二、push() 方法和 pop() 方法
push()方法用于向数组末尾添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['苹果', '香蕉'];
const res = fruits.push('橘子', '西瓜');
console.log(fruits); //[ '苹果', '香蕉', '橘子', '西瓜' ]
console.log(res); //4
const fruits = ['苹果', '香蕉', '橘子'];
const lastFruit = fruits.pop();
console.log(fruits); // ['苹果', '香蕉']
console.log(lastFruit); //橘子
三、shift() 方法和 unshift() 方法
shift() 方法用于删除并返回数组的第一个元素。
const fruits = ['苹果', '香蕉', '橘子'];
const firstFruit = fruits.shift();
console.log(fruits); //[ '香蕉', '橘子' ]
console.log(firstFruit); //苹果
unshift() 方法用于向数组的开头添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['苹果', '香蕉'];
const newLength = fruits.unshift('橘子', '西瓜');
console.log(fruits); //[ '橘子', '西瓜', '苹果', '香蕉' ]
console.log(newLength); //4
四、slice() 方法
slice() 方法用于从数组中截取指定位置的元素,返回一个新的数组。
语法是:array.slice(start, end),其中,start和end都是可选参数,表示选取的元素的起始位置和结束位置。如果不传入参数则默认选取整个数组。该方法返回的是一个新的数组,包含从start到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); //[ '李四', '王五' ]
co