返回

在编程中灵活用好数组方法,提高编码效率

前端

forEach - 遍历数组

const fruits = ["apple", "orange", "banana"];

fruits.forEach((fruit) => {
  console.log(`I like ${fruit}.`);
});

输出结果:

I like apple.
I like orange.
I like banana.

map - 创建新数组

const numbers = [1, 2, 3, 4, 5];

const doubledNumbers = numbers.map((number) => {
  return number * 2;
});

console.log(doubledNumbers); // [2, 4, 6, 8, 10]

filter - 过滤数组

const ages = [18, 21, 25, 30, 35, 40];

const adults = ages.filter((age) => {
  return age >= 21;
});

console.log(adults); // [21, 25, 30, 35, 40]

reduce - 累积数组元素

const numbers = [1, 2, 3, 4, 5];

const total = numbers.reduce((previousValue, currentValue) => {
  return previousValue + currentValue;
}, 0);

console.log(total); // 15

some - 检查数组元素是否满足条件

const ages = [18, 21, 25, 30, 35, 40];

const isSomeoneYoungerThan20 = ages.some((age) => {
  return age < 20;
});

console.log(isSomeoneYoungerThan20); // false

every - 检查数组元素是否全部满足条件

const ages = [18, 21, 25, 30, 35, 40];

const areAllAdults = ages.every((age) => {
  return age >= 18;
});

console.log(areAllAdults); // true

concat - 合并数组

const fruits1 = ["apple", "orange", "banana"];
const fruits2 = ["pineapple", "grape", "strawberry"];

const allFruits = fruits1.concat(fruits2);

console.log(allFruits); // ["apple", "orange", "banana", "pineapple", "grape", "strawberry"]

slice - 复制数组的一部分

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const slicedNumbers = numbers.slice(2, 5);

console.log(slicedNumbers); // [3, 4, 5]

sort - 对数组进行排序

const numbers = [1, 5, 3, 7, 2, 4, 9, 6, 8, 10];

numbers.sort((a, b) => {
  return a - b;
});

console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

join - 将数组元素连接成字符串

const fruits = ["apple", "orange", "banana"];

const fruitString = fruits.join(", ");

console.log(fruitString); // "apple, orange, banana"

push - 向数组末尾添加元素

const fruits = ["apple", "orange", "banana"];

fruits.push("pineapple");

console.log(fruits); // ["apple", "orange", "banana", "pineapple"]

pop - 从数组末尾删除元素

const fruits = ["apple", "orange", "banana"];

fruits.pop();

console.log(fruits); // ["apple", "orange"]

shift - 从数组开头删除元素

const fruits = ["apple", "orange", "banana"];

fruits.shift();

console.log(fruits); // ["orange", "banana"]

unshift - 向数组开头添加元素

const fruits = ["apple", "orange", "banana"];

fruits.unshift("pineapple");

console.log(fruits); // ["pineapple", "apple", "orange", "banana"]

splice - 删除或添加数组元素

const fruits = ["apple", "orange", "banana", "pineapple", "grape"];

fruits.splice(2, 2); // 删除从索引2开始的两个元素

console.log(fruits); // ["apple", "orange", "grape"]

fruits.splice(1, 0, "strawberry", "blueberry"); // 在索引1处添加两个元素

console.log(fruits); // ["apple", "strawberry", "blueberry", "orange", "grape"]

通过掌握这些数组方法,您将能够更有效地处理数据,编写更加清晰、简洁的代码。这些方法是JavaScript数组的基础,理解并灵活运用它们对于提高编程效率至关重要。希望本文能够帮助您进一步提升编程技能,祝您编码愉快!