您好!欢迎来到源码码网

JavaScript 20种数组方法介绍

  • 源码教程
  • 来源:源码码网
  • 编辑:admin
  • 时间:2023-04-13 09:45
  • 阅读:273

JavaScript中的Array对象与其他编程语言中的数组一样,可以将多个项目的集合存储在单个变量名下,并具有用于执行常见数组操作的成员。

image.png

声明数组

有两种不同的方式可以声明数组。

使用new Array

通过new Array,我们可以指定希望存在于数组中的元素,如下所示:

const fruits = new Array('Apple''Banana');
console.log(fruits.length);

数组字面量表示法

使用数组字面量声明,我们可以指定数组将具有的值。如果我们不声明任何值,则数组将为空。

// 通过数组字面量创建一个有2个元素的'fruits'数组.
const fruits = ['Apple''Banana'];
console.log(fruits.length);

以下是Array对象的方法列表及描述。

1. forEach

forEach()方法将为每个数组元素执行一次指定的函数。

forEach()为数组中的每个元素按索引升序调用提供的callbackFn函数一次。它不会为已删除或未初始化的索引属性调用。

array.forEach(callback[, thisObject]);
const array1 = ['a''b''c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

2. map

Array.map()方法允许你遍历数组并使用回调函数修改其元素。然后将在数组的每个元素上执行回调函数。

array.map(callback[, thisObject]);
let arr = [3456];

let modifiedArr = arr.map(function(element){
    return element *3;
});

console.log(modifiedArr); // [9, 12, 15, 18]

Array.map()方法通常用于对元素应用一些更改,无论是像在上面代码中那样乘以特定数字,还是执行应用程序可能需要的任何其他操作。

3. concat

JavaScript中的concat()方法是一个字符串方法,用于将字符串连接在一起。concat()方法将一个或多个字符串值附加到调用字符串,然后将连接的结果作为新字符串返回。因为concat()方法是String对象的方法,所以必须通过String类的特定实例来调用它。

array.concat(value1, value2, ..., valueN);
const array1 = ['a''b''c'];
const array2 = ['d''e''f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

4. push

Javascript数组中的push()方法将给定元素附加到数组最后并返回新数组的长度。

如果你想在数组末尾添加一个元素,请使用push()

array.push(element1, ..., elementN);
const countries = ["Nigeria""Ghana""Rwanda"];

countries.push("Kenya");

console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]

5. pop

pop()方法将删除数组的最后一个元素并将该值返回给调用者。如果你在空数组上调用pop(),则返回undefined

Array.prototype.shift()pop()具有相似的行为,但应用于数组中的第一个元素。

array.pop();
const plants = ['broccoli''cauliflower''cabbage''kale''tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

6. splice

splice()方法是一种通用方法,用于在数组的指定位置通过删除、替换或添加元素来更改数组的内容。本节将介绍如何使用此方法将元素添加到特定位置。

array.splice(index, howMany, [element1][, ..., elementN]);
const fruits = ["Banana""Orange""Apple""Mango"];

fruits.splice(20"Lemon""Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango

7. slice

slice()方法将一部分数组的浅表副本返回到从开始到结束(不包括结束)选择的新数组对象中,其中开始和结束表示该数组中项目的索引。该方法不会修改原始数组。

array.slice( begin [,end] );
const animals = ['ant''bison''camel''duck''elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(24));
// expected output: Array ["camel", "duck"]

8. shift

shift()是内置的JavaScript函数,用于从数组中删除第一个元素。shift()函数直接修改正在使用的数组。同时shift()返回数组中删除的项目。

shift()函数删除索引位置0的项目,并将索引号的值依次向下移动1。

array.shift();
const array1 = [123];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

9. unshift

unshift()方法将插入给定值到类数组对象的开头。

Array.prototype.push()unshift()具有相似的行为,但应用于数组的末尾。

array.unshift( element1, ..., elementN );
const array1 = [123];

console.log(array1.unshift(45));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]

10. join

JavaScript数组中的join()方法是一个内置方法,通过连接数组的所有元素来创建并返回新字符串。join()方法将连接数组的项到字符串并返回该字符串。指定的分隔符用于分隔元素数组。默认分隔符是逗号(,)。

array.join(separator);
const elements = ['Fire''Air''Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

11. every

every()方法测试数组中的所有元素是否都满足指定的条件。返回的是布尔值。

array.every(callback[, thisObject]);
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [13039291013];

console.log(array1.every(isBelowThreshold));
// expected output: true

12. filter

filter()方法创建部分给定数组的浅表副本,向下过滤到给定数组中的元素,且元素通过所提供函数实现的条件测试。

array.filter(callback[, thisObject]);
const words = ['spray''limit''elite''exuberant''destruction''present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

13. indexOf

indexOf()方法返回可以在数组中找到给定元素的第一个索引,如果不存在则返回-1。

array.indexOf(searchElement[, fromIndex]);
const beasts = ['ant''bison''camel''duck''bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison'2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

14. reduce

reduce()方法按顺序对数组的每个元素执行用户提供的reducer回调函数,传入前一个元素的计算返回值。在数组的所有元素上运行reducer的最终结果是单个值。

array.reduce(callback[, initialValue]);
const array1 = [1234];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial)

15. reverse

reverse()方法将反转数组并返回对相同数组的引用,第一个数组元素成为最后一个,最后一个数组元素成为第一个。换句话说,数组中的元素顺序将转向与之前相反的方向。

array.reverse();
const array1 = ['one''two''three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

16. sort

sort()方法对数组的元素进行就地排序,并返回对同一个数组的引用,而此时数组已排序。默认排序顺序是升序,将元素转换为字符串,然后比较它们的UTF-16代码单元值序列。

array.sort( compareFunction );
const months = ['March''Jan''Feb''Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [130421100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

17. toString

toString()方法返回表示对象的字符串。

array.toString();
function Dog(name{
  this.name = name;
}

const dog1 = new Dog('Gabby');

Dog.prototype.toString = function dogToString({
  return `${this.name}`;
};

console.log(dog1.toString());
// expected output: "Gabby"

18. at

at()方法接受整数值并返回at索引的项目,正整数和负整数皆可。负整数从数组中的最后一项开始倒数。

array.at(index)
const array1 = [512813044];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

19. find

find()方法返回数组中满足条件测试函数的第一个元素。如果没有值满足提供的测试函数,则返回undefined

array.find(function(currentValue, index, arr),thisValue)
const array1 = [512813044];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

20. some

some()方法测试数组中是不是至少有一个元素通过了函数实现的条件测试。如果在数组中找到这样的元素就返回true;否则返回false。该方法不修改原数组。

array.some(callback[, thisObject]);
const array = [12345];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true


特别声明:
1、如无特殊说明,内容均为本站原创发布,转载请注明出处;
2、部分转载文章已注明出处,转载目的为学习和交流,如有侵犯,请联系客服删除;
3、编辑非《源码码网》的文章均由用户编辑发布,不代表本站立场,如涉及侵犯,请联系删除;
全部评论(0)
推荐阅读
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统的用户登录状态保存需要综合考虑安全性、用户体验和系统架构。以下是企业级的完整方案:1.多层级存储策略class AuthManager {    constructor() {        this.storage = { &n
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-11-06 12:16
  • 阅读:350
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 在数字经济蓬勃发展的今天,源码交易市场已成为互联网创业者和开发商的重要资源池。从电商系统源码到社交应用框架,从小程序解决方案到企业级管理系统,越来越多的开发者、初创企业和传统商家通过源码交易平台快速获取技术资产,实现商业目标的加速。源码交易市场的繁荣反映了数字化转型的迫切需求——企业需要快速迭代,开发者需要快速变现,用户需要快速启动。然而,在这个高速发展的市场中,一个长期被忽视但至关重要的问题浮现出来:支付系统的效率与安全性已成为制约交
  • 行业资讯
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-23 15:16
  • 阅读:295
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • 在SpringBoot工程编译时遇到maven-surefire-plugin的测试执行失败错误(Failedtoexecutegoalorg.apache.maven.plugins:maven-surefire-plugin:3.5.3:test),通常与测试环节相关。以下是常见原因及解决方法:1.测试用例执行失败• 原因:最常见的是测试用例(*Test.java)运行时抛出异常(如断言失败、空指针等),导
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-13 10:57
  • 阅读:361
  • WeMark - 微信小程序图片水印
  • WeMark - 微信小程序图片水印
  • 一个纯前端的微信小程序图片水印工具。支持文字/图片水印、单个与全屏两种模式,透明度与角度调节、单个水印位置X/Y控制,预览与对比模态、历史记录(100条)等功能。
  • 源码教程
  • 来源:源码码用户
  • 编辑:yg
  • 时间:2025-09-22 16:09
  • 阅读:283
联系客服
源码代售 源码咨询 素材咨询 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部