JS中数组22种常用API总结,slice、splice、map、reduce、shift、filter、indexOf......

本文总结了JavaScript中数组的22种常用API,包括push()、pop()、shift()、unshift()、slice()、splice()、join()、concat()、forEach()、map()、filter()、reduce()、fill()、查找方法(includes()、indexOf()、lastIndexOf()、findIndex())、sort()、reverse()、toString()、toLocaleString()和Array.from()。这些API帮助开发者高效地操作和处理数组数据。
摘要由CSDN通过智能技术生成

一、引言

在前端开发中,数组是一种常见且重要的数据结构。数组提供了许多便捷的方法来操作和处理其中的数据。本文将简单介绍前端中数组常用的API,包括添加、删除、截取、合并、转换等操作。

二、push() 方法和 pop() 方法

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

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

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值