0

0

每个开发人员都应该掌握的 JavaScript 数组方法(第 1 部分)

PHPz

PHPz

发布时间:2024-09-07 21:17:03

|

1194人浏览过

|

来源于dev.to

转载

每个开发人员都应该掌握的 javascript 数组方法(第 1 部分)

“能力越大,责任越大。”
— 本叔叔,蜘蛛侠 (2002)

就像蜘蛛侠必须掌握他新发现的能力一样,开发人员需要掌握 javascript 强大的数组方法才能高效、负责任地进行编码。

让我们深入研究一些必须知道的数组方法!

1. 查找

find() 方法返回满足所提供的测试函数的第一个数组元素的值。

arr.find(callback(element, index, arr),thisarg)

立即学习Java免费学习笔记(深入)”;

  • 返回数组中满足给定函数的第一个元素
  • 如果没有元素满足该函数,则返回未定义
const cuties = [
  { name: "wanda maximoff", age: 31 },
  { name: "natasha romanoff", age: 32 },
  { name: "jane foster", age: 27 },
  { name: "gwen stacy", age: 26 },
];

// find method returns the value of the first element 
// in the array that satisfies the given function 
// or else returns undefined
let cuty = cuties.find(({ age }) => age >= 30);

// output: { name: 'wanda maximoff', age: 31 }
console.log(cuty);

2. 查找索引

findindex() 方法返回满足所提供的测试函数的第一个数组元素的索引,否则返回 -1。

arr.findindex(callback(element, index, arr),thisarg)

  • 返回数组中满足给定函数的第一个元素索引
  • 如果没有元素满足该函数,则返回-1
const cuties = [
  { name: "wanda maximoff", age: 31 },
  { name: "natasha romanoff", age: 32 },
  { name: "jane foster", age: 27 },
  { name: "gwen stacy", age: 26 },
];

// findindex method returns the index of the first array element 
// that satisfies the provided test function or else returns -1.
let cutyindex = cuties.findindex(({ age }) => age >= 30);

// output: 0
console.log(cutyindex);

3.索引

indexof() 方法返回数组元素出现的第一个索引,如果未找到,则返回 -1。

arr.indexof(searchelement, fromindex)

  • 如果元素在数组中至少出现一次,则返回该元素的第一个索引。
  • 如果在数组中未找到该元素,则返回-1
const productprices = [5, 12, 3, 20, 5, 2, 50];

// indexof() returns the first index of occurance 
// of an array element, or -1 if it is not found.
let firstindex = productprices.indexof(20);
console.log(firstindex); // 3

let secondindex = productprices.indexof(5);
console.log(secondindex); // 0

// the second argument specifies the search start index
let thirdindex = productprices.indexof(5, 1);
console.log(thirdindex); // 4

// indexof returns -1 if not found
let notfoundindex = productprices.indexof(15);
console.log(notfoundindex); // -1

4. 排序

sort() 方法按特定顺序(升序或降序)对数组的项目进行排序。

arr.sort(comparefunction)

  • 对数组元素进行排序后返回数组(这意味着它更改了原始数组并且不进行复制)。
const avengers = ["captain", "tony", "thor", 
                  "natasha", "bruce", "clint"];

// modifies the array in place
avengers.sort(); 

// [ 'bruce', 'captain', 'clint', 'natasha', 'thor', 'tony' ]
console.log(avengers);  

const nums = [1000, 50, 2, 7, 14];

// number is converted to string and sorted
nums.sort(); 

// output: [ 1000, 14, 2, 50, 7 ]
console.log(nums) 

// sort nums in ascending order by providing compare function
nums.sort((a, b) => a - b);

// output: [ 2, 7, 14, 50, 1000 ]
console.log(nums);

5. 包括

includes() 方法检查数组是否包含指定元素。

arr.includes(valuetofind, fromindex)

includes() 方法返回:

  • 如果在数组 searchvalue
  • 中的任何位置找到,则为 true
  • 如果在数组 searchvalue 中找不到任何位置,则返回 false
const avengers = ["captain", "tony", "thor", 
                 "natasha", "bruce", "clint"];

// includes() method returns true if an array contains 
// a specified element or else returns false.
let check1 = avengers.includes("thor");
console.log(check1); // true 

// second argument specifies position to start the search
let check2 = avengers.includes("thor", 3);
console.log(check2); // false

// the search starts from the 4th-to-last element ("hulk") 
// and checks the rest of the array for "thor". 
let check3 = avengers.includes("thor", -4);
console.log(check3); // true

6. foreach

foreach() 方法为每个数组元素执行提供的函数。

arr.foreach(callback(currentvalue), thisarg)

企奶奶
企奶奶

一款专注于企业信息查询的智能大模型,企奶奶查企业,像聊天一样简单。

下载

• foreach() 不会对没有值的数组元素执行回调。

• 返回未定义。

const nums = [120, 150, 80, , 200];

// foreach() method executes a provided 
// function for each array element which 
// have values. it returns undefined.

/*
num 0: 120
num 1: 150
num 2: 80
num 4: 200
*/
nums.foreach((value, index) => {
    console.log('num ' + index + ': ' + value);
});

7. 切片

slice() 方法将数组的一部分的浅拷贝返回到新的数组对象中。

arr.slice(开始, 结束)

• 返回包含提取元素的新数组。

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

// slicing the array (from start to end)
let slicedfruits1 = fruits.slice();
console.log(slicedfruits1); // [ 'apple', 'banana', 'orange', 'grape', 'mango' ]

// slicing from the third element
let slicedfruits2 = fruits.slice(2);
console.log(slicedfruits2); // [ 'orange', 'grape', 'mango' ]

// slicing from the second element to fourth element
let slicedfruits3 = fruits.slice(1, 4);
console.log(slicedfruits3); // [ 'banana', 'orange', 'grape' ]

// slicing the array from start to second-to-last
let slicedfruits4 = fruits.slice(0, -1);
console.log(slicedfruits4); // [ 'apple', 'banana', 'orange', 'grape' ]

// slicing the array from third-to-last
let slicedfruits5 = fruits.slice(-3);
console.log(slicedfruits5); // [ 'orange', 'grape', 'mango' ]

8. 拼接

splice() 方法修改数组(添加、删除或替换元素)。

arr.splice(start, deletecount, item1, ..., itemn)

• 返回包含已删除元素的数组。

let animals = ["dog", "cat", "elephant", "lion"];

// replacing "elephant" & "lion" with "tiger" & "giraffe"
let removedanimals1 = animals.splice(2, 2, "tiger", "giraffe");
console.log(removedanimals1); // [ 'elephant', 'lion' ]
console.log(animals); // [ 'dog', 'cat', 'tiger', 'giraffe' ]

// adding elements without deleting existing elements
let removedanimals2 = animals.splice(1, 0, "elephant", "lion");
console.log(removedanimals2); // []
console.log(animals); // [ 'dog', 'elephant', 'lion', 'cat', 'tiger', 'giraffe' ]

// removing 3 elements
let removedanimals3 = animals.splice(2, 3);
console.log(removedanimals3); // [ 'lion', 'cat', 'tiger' ]
console.log(animals); // [ 'dog', 'elephant', 'giraffe' ]

9. 每个

every() 方法检查所有数组元素是否通过给定的测试函数。

arr.every(callback(currentvalue), thisarg)

every() 方法返回:

  • true - 如果所有数组元素都通过给定的测试函数(回调返回真值)。
  • false - 如果任何数组元素未通过给定的测试函数。
const nums1 = [ 1 , 2 , 3 , 4 , 5];

// every() method returns true if all the array 
// elements pass the given test function or else
// returns false
let result1 = nums1.every(element => element < 6);

// output: true
console.log(result1); 

const nums2 = [ 1 , 2 , 7 , 4 , 5];
let result2 = nums2.every(element => element < 6);

// output: false
console.log(result2);

10.一些

some() 方法测试是否有任何数组元素通过给定的测试函数。

arr.some(callback(currentvalue), thisarg)

  • 如果数组元素通过给定的测试函数,则返回 true(回调返回真值)。
  • 否则返回 false
const nums1 = [ 8 , 2 , 7 , 9 , 6];

// some() method returns true if any of the array 
// elements pass the given test function or else 
// returns false
let result1 = nums1.some(element => element < 6);

// Output: true
console.log(result1); 

const nums2 = [ 8 , 6 , 7 , 9 , 10];
let result2 = nums2.some(element => element < 6);

// Output: false
console.log(result2);

请继续关注我们系列的第 2 部分,我们将深入探讨更重要的 javascript 数组方法!快乐学习!

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
sort排序函数用法
sort排序函数用法

sort排序函数的用法:1、对列表进行排序,默认情况下,sort函数按升序排序,因此最终输出的结果是按从小到大的顺序排列的;2、对元组进行排序,默认情况下,sort函数按元素的大小进行排序,因此最终输出的结果是按从小到大的顺序排列的;3、对字典进行排序,由于字典是无序的,因此排序后的结果仍然是原来的字典,使用一个lambda表达式作为key参数的值,用于指定排序的依据。

391

2023.09.04

php中foreach用法
php中foreach用法

本专题整合了php中foreach用法的相关介绍,阅读专题下面的文章了解更多详细教程。

74

2025.12.04

go语言 数组和切片
go语言 数组和切片

本专题整合了go语言数组和切片的区别与含义,阅读专题下面的文章了解更多详细内容。

46

2025.09.03

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

10

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

109

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

16

2026.01.26

苹果官方查询网站 苹果手机正品激活查询入口
苹果官方查询网站 苹果手机正品激活查询入口

苹果官方查询网站主要通过 checkcoverage.apple.com/cn/zh/ 进行,可用于查询序列号(SN)对应的保修状态、激活日期及技术支持服务。此外,查找丢失设备请使用 iCloud.com/find,购买信息与物流可访问 Apple (中国大陆) 订单状态页面。

138

2026.01.26

npd人格什么意思 npd人格有什么特征
npd人格什么意思 npd人格有什么特征

NPD(Narcissistic Personality Disorder)即自恋型人格障碍,是一种心理健康问题,特点是极度夸大自我重要性、需要过度赞美与关注,同时极度缺乏共情能力,背后常掩藏着低自尊和不安全感,影响人际关系、工作和生活,通常在青少年时期开始显现,需由专业人士诊断。

7

2026.01.26

windows安全中心怎么关闭 windows安全中心怎么执行操作
windows安全中心怎么关闭 windows安全中心怎么执行操作

关闭Windows安全中心(Windows Defender)可通过系统设置暂时关闭,或使用组策略/注册表永久关闭。最简单的方法是:进入设置 > 隐私和安全性 > Windows安全中心 > 病毒和威胁防护 > 管理设置,将实时保护等选项关闭。

6

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号