javascript常用方法之Array篇
1.数组元素的添加和删除
(1)push()
作用: 在数组的末尾添加一个或多个元素,并返回新的数组长度
const fruits = ['apple', 'banana'];
const newLength = fruits.push('cherry');
console.log(fruits); // 输出: ['apple', 'banana', 'cherry']
console.log(newLength); // 输出: 3
(2) pop()
作用:移除数组的最后一个元素,并返回该元素
const fruits = ['apple', 'banana', 'cherry'];
const lastFruit = fruits.pop();
console.log(fruits); // 输出: ['apple', 'banana']
console.log(lastFruit); // 输出: 'cherry'
(3) unshift() 和shift()
unshift():在数组的开头添加一个或多个元素,并返回新的数组长度
shift():移除数组的第一个元素,并返回该元素
const fruits = ['banana', 'cherry'];
const newLength = fruits.unshift('apple');
console.log(fruits); // 输出: ['apple', 'banana', 'cherry']
console.log(newLength); // 输出: 3
------------------------------------------------------------
const fruits = ['apple', 'banana', 'cherry'];
const firstFruit = fruits.shift();
console.log(fruits); // 输出: ['banana', 'cherry']
console.log(firstFruit); // 输出: 'apple'
2.数组的拆分与合并
(1)concat()
作用:用于连接两个或多个数组,不会更改现有数组,而是返回一个新数组,其中包含已连接数组的值
var sedan = ["S60", "S90"];
var SUV = ["XC40", "XC60", "XC90"];
var wagon = ["V60", "V90", "V90CC"];
var Volvo = sedan.concat(SUV,wagon);
console.log(Volvo);//输出:S60,S90,XC40,XC60,XC90,V60,V90,V90CC
(2) slice()
返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象,原数组不变
const fruits = ['apple', 'banana', 'cherry', 'date'];
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // 输出: ['banana', 'cherry']
(3)splice()
通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
const fruits = ['apple', 'banana', 'cherry', 'date'];
// 从索引 1 开始删除 2 个元素,并插入 'grape' 和 'lemon'
const removedFruits = fruits.splice(1, 2, 'grape', 'lemon');
console.log(fruits); // 输出: ['apple', 'grape', 'lemon', 'date']
console.log(removedFruits); // 输出: ['banana', 'cherry']
(4)toSplice()
用于删除或替换数组元素,返回一个新数组,不会改变原始数组
// 创建一个数组
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// 在位置 2,移除 1 个元素,添加 "Lemon" 和 "Kiwi"
const fruits2 = fruits.toSpliced(2, 1, "Lemon", "Kiwi");
console.log(fruits); // 输出: [Banana,Orange,Apple,Mango]
console.log(fruits2); // 输出: [Banana,Orange,Lemon,Kiwi,Mango]
(5)with()
用于更新数组中指定的元素,不会改变原始数组,返回新数组
const months = ["Januar", "Februar", "Mar", "April"];
const myMonths = months.with(2, "March");
console.log(myMonths)//输出:Januar,Februar,March,April
3.数组的查找和过滤
(1)indexOf()
返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回 -1
const fruits = ['apple', 'banana', 'cherry'];
const index = fruits.indexOf('banana');
console.log(index); // 输出: 1
(2)includes()
判断一个数组是否包含一个指定的值,如果包含则返回 true
,否则返回 false
const fruits = ['apple', 'banana', 'cherry'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // 输出: true
(3)filter()
创建一个新数组,其包含通过所提供函数实现的测试的所有元素
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
//这里隐藏了因为语法可以省略return,建议不省略(return num % 2 === 0)
console.log(evenNumbers); // 输出: [2, 4]
4.数组的遍历和映射
(1) forEach()
对数组的每个元素执行一次提供的函数
const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));
// 依次输出: 1 2 3
(2) map()
创建一个新数组,返回一个包含通过所提供函数实现的测试的所有元素
const numbers = [1, 2, 3];
const squaredNumbers = numbers.map(num => return num * num);
console.log(squaredNumbers); // 输出: [1, 4, 9]
5. 数组的排序和反转
(1)sort()
对数组的元素进行排序,并返回数组
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
numbers.sort((a, b) => a - b);
console.log(numbers); // 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
(2)reverse()
将数组中元素的位置颠倒,并返回该数组
const numbers = [1, 2, 3];
numbers.reverse();
console.log(numbers); // 输出: [3, 2, 1]
6.其他
(1)every()
检查数组中的所有元素是否都通过了测试,不改变原始数组
- 如果找到函数返回 false 值的数组元素,every() 返回 false(并且不检查剩余值)
- 如果没有出现 false,every() 返回 true
var ages = [32, 33, 16, 40];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
(2)some()
检查数组中的任何元素是否通过测试
- 如果找到函数返回真值的数组元素,some() 返回真(并且不检查剩余值),不改变原始数组
- 否则返回 false
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.some(checkAdult);
}
(3) join()
语法:array.join(separator) 参数separator可选。要使用的分隔符。如果省略,元素用逗号分隔
将数组作为字符串返回
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();
console.log(energy);//输出Banana,Orange,Apple,Mango
var energy1 = fruits.join(" and ")
console.log(energy1);//输出Banana and Orange and Apple and Mango
(4)reduce()
reduce 是数组的一个高阶方法,它可以对数组中的每个元素执行一个自定义的回调函数,并将结果汇总为单个值。这个方法非常强大,可用于各种数据处理任务,如求和、求积、合并数组等。
语法:array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
callback
:这是一个必需的回调函数,用于对数组元素进行处理。它接受四个参数:accumulator
:累加器,用于存储上一次回调函数的返回值,或者是初始值(如果提供了initialValue
)。currentValue
:当前正在处理的数组元素。currentIndex
:当前元素的索引。array
:调用reduce
方法的数组本身。
initialValue
:可选参数,作为第一次调用callback
时的accumulator
的初始值。如果没有提供initialValue
,则使用数组的第一个元素作为初始值,并且从数组的第二个元素开始执行callback
。
常见使用场景
数组求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出: 15
数组求积
const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1);
console.log(product); // 输出: 120
数组合并
const arrays = [[1, 2], [3, 4], [5, 6]];
const mergedArray = arrays.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(mergedArray); // 输出: [1, 2, 3, 4, 5, 6]
统计数组中元素的出现次数
const fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const fruitCount = fruits.reduce((accumulator, currentValue) => {
if (accumulator[currentValue]) {
accumulator[currentValue]++;
} else {
accumulator[currentValue] = 1;
}
return accumulator;
}, {});
console.log(fruitCount);
// 输出: { apple: 3, banana: 2, cherry: 1 }