ES6中数组首尾两端和中间添加/移除数据方法

本文深入讲解JavaScript中数组的常用操作,包括push()尾端插入、pop()尾端移除、shift()首端移除、unshift()首端插入以及如何使用拓展运算符实现数组任意位置的元素插入。通过实例演示,帮助读者掌握数组操作的基础知识。

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

1、push() 尾端插入,返回数组长度

let arr = [1,"hello",true];
console.log(arr.push(22));//4
console.log(arr,'---arr');//[1, "hello", true, 22]
console.log(arr.push(false,123));//6
console.log(arr,'---arr2');//[1, "hello", true, 22, false, 123]
console.log(arr.push(["a","b"]));//7
console.log(arr,'---arr3');//[1, "hello", true, 22, false, 123, ["a","b"]]

2、pop() 尾端移除,返回移除项

let arr = [2,"hello",true];
console.log(arr.pop());//true
console.log(arr,'---arr');//[2, "hello"]
//里面无需加参数,加参数没用
console.log(arr.pop(0));//hello
console.log(arr,'---arr2');//[2]

3、shift() 首端移除,返回移除项

let arr = [1,"hello",true];
console.log(arr.shift());//1
console.log(arr,'---arr');//["hello", true]

4、unshift() 首端插入,返回数组长度

let arr = [1,"hello",true];
console.log(arr.unshift(false,123));//5
console.log(arr,'---arr');//[false, 123, 1, "hello", true]
console.log(arr.unshift());//5
console.log(arr,'---arr2');//[false, 123, 1, "hello", true]

5、利用拓展运算符(...)可实现在数组前中后插入数据

let arr = [2,"hello",true];
var arr2 = [...arr,"a",...arr,"b",...arr]
console.log(arr2)// [2, "hello", true, "a", 2, "hello", true, "b", 2, "hello", true]

 

ES6引入了一些新的数组循环方法,它们比传统的for循环更简洁易读。以下是几种常用的数组循环方法: 1. **forEach**: 这是最简单的遍历数组的方式,对每个元素执行一次提供的回调函数。例子: ```javascript const arr = [1, 2, 3]; arr.forEach(item => console.log(item)); ``` 2. **map**: 对数组中的每个元素应用一个函数,并返回一个新的数组,新数组包含原始元素经过操作后的结果。例子: ```javascript const newArr = arr.map(num => num * 2); // 新数组为 [2, 4, 6] ``` 3. **filter**: 创建一个新数组,只包含通过指定测试的所有元素。例子: ```javascript const filteredArr = arr.filter(num => num % 2 === 0); // 新数组只包含偶数 ``` 4. **reduce**: 将数组缩减成单个值,通过累加、合并或其他函数对每个元素应用一个操作。例子: ```javascript const sum = arr.reduce((total, num) => total + num, 0); // 计算数组所有元素之 ``` 5. **some**: 判断数组是否有满足条件的元素,如果有则返回true,否则返回false。例子: ```javascript const hasEven = arr.some(num => num % 2 === 0); ``` 6. **every**: 检查数组中的所有元素是否都满足某个条件,如果有任何一个不满足,则返回false。例子: ```javascript const areAllPositive = arr.every(num => num > 0); ``` 7. **find**: 找到数组中满足指定条件的第一个元素,若无符合条件的元素则返回undefined。例子: ```javascript const firstPositive = arr.find(num => num > 0); ``` 8. **findIndex**: 类似于find,但它返回的是符合条件的第一个元素的索引。例子: ```javascript const indexOfFirstPositive = arr.findIndex(num => num > 0); ``` 9. **Array.from() Array.of()**: 可以用于将其他可迭代对象转换成数组。比如: ```javascript const iterableObj = {0: 'a', 1: 'b'}; const newArray = Array.from(iterableObject); ``` 以上就是ES6中常用的数组循环方法,它们提高了代码的可读性性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值