js 关于数组的操作方法大全

本文详细介绍了JavaScript中常用的数组操作方法,包括concat合并数组、fill填充数组、filter过滤数组、find查找元素、forEach遍历数组等17种方法的使用技巧及示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.concat 合并数组
var a = [1,2,3,2,3,3]
var b = [5,6,8]
var c = a.concat(b)
console.log(c)//[1, 2, 3, 2, 3, 3, 5, 6, 8]
2.fill 使用固定值填充数组
var arr = [1,2,3,4,5]
var b = arr.fill(3)
console.log(b)//[3, 3, 3, 3, 3]
3.filter 过滤 返回数组中所有满足条件的值 返回类型是Array
var arr = [1,2,3,2,3,3]
var b = arr.filter(item=>item==3)
console.log(b)//[3, 3, 3]
4.find 查找对象,返回数组中满足条件的第一个值 返回类型是对象内的元素类型
var arr = [1,2,3,2,3,3]
var b = arr.find(item=>item==3)
console.log(b)//3
5.findIndex 查找对象 返回第一个满足条件的元素的下标
var arr = [1,2,3,2,3,3]
var b = arr.findIndex(item=>item==3)
console.log(b)//2
6.forEach 遍历数组
var arr = [1,2,3,2,3,3]
var b = arr.forEach((item,index)=>{
	console.log(item,index)
})
console.log(b)
7.indexOf 查找数组中是否有满足条件的值,有返回1,无返回-1
var arr = [1,2,3,2,3,3]
var b = arr.indexOf(2)
console.log(b)//1
8.includes 查找数组中是否有满足条件的值,有返回true,无返回false
var arr = [1,2,3,2,3,3]
var b = arr.includes(5)
var c = arr.includes(3)
console.log(b)//false
console.log(c)//true
9.join 将数组元素连成字符串,连接符自己传入,返回类型String
var a = [1,2,3,2,3,3]
var c = a.join('/')
console.log(c)//1/2/3/2/3/3 
10.map 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素。
map() 不会对空数组进行检测。
map() 不会改变原始数组。

var a = [1,2,3,2,3,3]
var c = a.map((item,index)=>{
	return item + 1 
})
console.log(a)//[1, 2, 3, 2, 3, 3]
console.log(c)//[2, 3, 4, 3, 4, 4]
11.pop 删除数组最后一个元素 并返回删除的元素
var a = [1,2,3];
var b = a.pop()
console.log(b)//3
12.push 数组末尾添加元素
var a = [1,2,3];
a.push(6)
console.log(a)//[1, 2, 3, 6]
13.shift 删除数组第一个元素 并返回第一个元素
var a = [1,2,3];
var b = a.shift()
console.log(b)//1
14.slice 返回数组中选定的元素 返回数组
var a = [1,2,3,4,5,6];
var b = a.slice(1,4)
console.log(b)//[2, 3, 4]
15.sort 给数组排序 返回排好序的数组
var a = [3,1,5,2,4];
var b = a.sort()
console.log(b)//[1, 2, 3, 4, 5]
16.splice 方法用于添加或删除数组中的元素。
var a = [3,1,5,2,4];
var b = a.splice(1,3)
console.log(b)//[1, 5, 2]

var a = [3,1,5,2,4];
var b = a.splice(1,2,'ha','ha','ha')
console.log(b)//[1, 5] 返回的是删除掉的
console.log(a)//[3, "ha", "ha", "ha", 2, 4] a被改变了
17.unshift 数组头部插入值
var a = [3,1,5,2,4];
a.unshift(10)
console.log(a)//[10, 3, 1, 5, 2, 4]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值