reverse
reverse()
方法将数组中的元素的位置颠倒,并返回该数组。
该方法会改变原数组。
参数
没有参数
返回值
颠倒后的数组
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1); // ["one", "two", "three"]
const reversed = array1.reverse();
// 返回倒序数组
console.log('reversed:', reversed); // ["three", "two", "one"]
// 将原数组也改变成了倒序的
console.log('array1:', array1); // ["three", "two", "one"]
所以在使用reverse()
方法的时候,要先拷贝一份再操作:
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1); // ["one", "two", "three"]
const nextArrray = [...array1].reverse();
console.log(nextArrray); // ["three", "two", "one"]
console.log(array1); // ["one", "two", "three"]
concat
concat()
方法用于合并两个或者多个数组。
不会更改原数组,而是返回一个新数组
参数
可以是一个值、数组或者多个数组。
返回值
一个新的数组
将值连接到数组
const arr1 = [1, 2, 3];
const arr2 = arr1.concat(4);
console.log(arr2); // [1,2,3,4]
连接一个数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [1,2,3,4,5,6]
连接多个数组
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [7, 8, 9];
const arr4 = arr1.concat(arr2,arr3);
console.log(arr4); // [1,2,3,4,5,6,7,8,9]
注意:
- 如果数组中是对象,那么
concat
将对象的引用复制到新的数组,是一个浅拷贝。 - 如果数组中是基本类型数据,那么
concat
将里面的值复制到新的数组。
every
every()
方法测试一个数组内的所有元素是否都能通过某个指定的测试。返回一个布尔值。
不会改变原数组。
参数
- callback
用来测试每个元素的函数,它可以接收三个参数:- element
用于测试的当前值 - index(可选)
用于测试的当前值的索引 - array(可选)
调用every
的当前数组
- element
- thisArg
执行callback
时使用的this
值。
返回值
如果回调函数的每一次返回都为truthy
值,返回true
,否则返回false
。
案例1
const students = [
{
name: '张三',
age: 20,
},
{
name: '李四',
age: 19,
},
];
const res = students.every((student) => student.name && student.age > 18);
console.log(res); // true
fill
fill()
方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。
fill
方法会改变原数组
参数
- value
用来填充数组元素的值。 - start(可选)
起始索引,默认值为0,如果为负数,那么start = length + start - end(可选)
终止索引,默认值为this.length
如果为负数,那么end = length + end
返回值
修改后的数组。
改变原数组
const arr = [1,2,3,4,5];
// 从index=2开始,到结尾的数据都修改为"222"
const res = arr.fill("222",2);
console.log(res); // [1,2,"222","222","222"]
// 原数组被改变
console.log(arr); // [1,2,"222","222","222"]
filter
filter()
方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
不改变原数组
参数
- callback
用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:- element
数组中当前正在处理的元素。 - index(可选)
正在处理元素的索引 - array(可选)
调用了filter
的数组本身
- element
- thisArg(可选)
执行callback
时,用于this
的值
返回值
返回符合条件的值重新组成的数组。
const nums = [1, 2, 3, 4, 5];
const result = nums.filter((num) => num > 2);
console.log(result); // [3,4,5]
includes
includes()
方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true
,否则返回false
。
参数
- valueToFind
需要查找的元素值。 - fromIndex(可选)
从数组的fromIndex
索引开始查找。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜。
返回值
如果找到了,返回true
,反之false
。
const nums = [1, 2, 3, 4, 5];
const result = nums.includes(2)
console.log(result); // true