JS数组方法合集(含应用场景)

编程入门 行业动态 更新时间:2024-10-12 16:24:29

JS<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组方法合集(含应用场景)"/>

JS数组方法合集(含应用场景)

1.Array.push()

向数组的末尾添加一个或多个元素,并返回新的数组长度。原数组改变

const arr = ["apple", "orange", "grape"];
const arr_length = arr.push("banana");console.log("arr", arr, "arr_length", arr_length);
// arr: [ 'apple', 'orange', 'grape', 'banana' ] arr_length: 4

2.Array.pop()

删除并返回数组的最后一个元素,若该数组为空,则返回undefined。原数组改变。

const arr = ["apple", "orange", "grape"];
const del_data = arr.pop();console.log("arr:", arr, "del_data:", del_data);
// arr: [ 'apple', 'orange' ] del_data: grape

3.Array.unshift()

向数组的开头添加一个或多个元素,并返回新的数组长度。原数组改变

const arr = ["apple", "orange", "grape"];
const arr_length = arr.unshift("banana");console.log("arr:", arr, "arr_length:", arr_length);
// arr: [ 'banana', 'apple', 'orange', 'grape' ] arr_length: 4

4.Array.shift()

删除并返回数组的第一个元素,若该数组为空,则返回undefined。原数组改变。

const arr = ["apple", "orange", "grape"];
const del_data = arr.shift();console.log("arr:", arr, "del_data:", del_data);
// arr: [ 'orange', 'grape' ] del_data: apple

5.Array.concat(arr1,arr2,...)

合并多个数组,生成一个新数组,原数组不变

const arr1 = ["apple", "orange", "grape"];
const arr2 = ["banana", "watermelon"];
const arr3 = ["mango"];
const newArr = arr1.concat(arr2, arr3);console.log("newArr:", newArr);
// newArr: [ 'apple', 'orange', 'grape', 'banana', 'watermelon', 'mango' ]

6.Array.join()

将数组的每一项使用指定的字符连接成一个字符串。默认连接字符为","。不改变原数组

const arr = ["apple", "orange", "grape"];
const str1 = arr.join();
const str2 = arr.join("--");console.log("str1:", str1);
// str1: apple,orange,grapeconsole.log("str2:", str2);
// str2: apple--orange--grape

7.Array.reverse()

将数组倒序,改变原数组

const arr = ["one", "two", "three"];arr.reverse();console.log("arr:", arr);
// arr: [ 'three', 'two', 'one' ]

8.Array.sort(fun)

对数组排序。参数 fun 可选,必须是函数,规定排序顺序。原数组改变。

注:如果调用该方法时没有使用参数,将不会按照数值大小排序,按照字符编码的顺序进行排序。

如果想按照其他规则进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

  • 若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
  • 若 a 等于b,则返回 0。
  • 若 a 大于 b,则返回一个大于 0 的值。

简单点就是:比较函数两个参数 a 和 b,返回 a-b 升序,返回 b-a 降序

从小到大

const arr = [85, 22, 33, 66, 1, 9, 222];const sortMinToMax = function (a, b) {return a - b;};console.log("arr:", arr.sort(sortMinToMax));
// arr: [ 1,  9,  22, 33, 66, 85, 222 ]

从大到小

const arr = [85, 22, 33, 66, 1, 9, 222];console.log("arr:",arr.sort((a, b) => b - a));
// arr: [ 222, 85, 66, 33, 22,  9,  1 ]

按照数组对象中的某个值排序

const arrObj = [{name: "第一名",age: 23,},{name: "第二名",age: 18,},{name: "第三名",age: 28,},{name: "第四名",age: 15,},];const sortMinToMax = (key) => {return (a, b) => {return a[key] - b[key];};};console.log("arrObj:", arrObj.sort(sortMinToMax("age")));
/* arrObj: [{ name: '第四名', age: 15 },{ name: '第二名', age: 18 },{ name: '第一名', age: 23 },{ name: '第三名', age: 28 }] */

9.Array.map(function(currentValue,index,arr), thisValue)

  通过指定函数处理数组的每个元素,并返回处理后的新数组。不改变原数组

基础应用:

const arr = [2, 4, 6, 8];
const newArr = arr.map((item) => item * 2);console.log("newArr:", newArr);
// newArr: [ 4, 8, 12, 16 ]

多数组合并成一个新的数组对象:

const arr1 = ["吕大", "赵二", "关三", "典小四"];
const arr2 = ["公爵", "侯爵", "伯爵", "子爵"];const newArr = arr1.map((item, index) => {return {level: arr2[index],name: item,};});console.log("newArr:", newArr);
/* newArr: [{ level: '公爵', name: '吕大' },{ level: '侯爵', name: '赵二' },{ level: '伯爵', name: '关三' },{ level: '子爵', name: '典小四' }] */

拼接数组里的多个键值

const arr = [{ level: "公爵", name: "吕大" },{ level: "侯爵", name: "赵二" },{ level: "伯爵", name: "关三" },{ level: "子爵", name: "典小四" },];const newArr = arr.map((item) => `${item["level"]}${item["name"]}`);console.log("newArr:", newArr);// newArr: [ '公爵吕大', '侯爵赵二', '伯爵关三', '子爵典小四' ]

map中的第二个参数thisValue的应用

const arr = [2, 4, 6, 8];/* 该this参数将在回调函数中使用。默认情况下,其值为undefined。这里this值更改为数字10,如果不写this指向的是全局 */const newArr = arr.map(function (item) {return item * this;}, 10);console.log("newArr:", newArr);
// newArr: [ 20, 40, 60, 80 ]

10.Array.slice(start,end)

按照条件查找出其中的部分内容,返回一个新的数组,包含从 start(包括该元素) 到 end (不包括该元素)的 Array 中的元素。不改变原数组。

array.slice(n) 第二个参数省略,则一直查找到末尾

array.slice(0)原样输出内容,可以实现数组克隆

array.slice(-n,-m) slice支持负参数,从最后一项开始算起,-1为最后一项,-2为倒数第二项

const arr = [2, 4, 6, 8];
const newArr = arr.slice(1, 3);console.log("newArr:", newArr);
// newArr: [ 4, 6 ]

11.Array.splice(index,howmany,item1,item2…)

从数组中添加或删除元素。改变原数组。

从index位置开始删除howmany个元素,并将item1、item2…数据从index位置依次插入。howmany为0时,则不删除元素。

const arr = ["吕大", "赵二", "关三", "典小四"];arr.splice(2, 1, "杰尼龟", "皮卡丘");console.log("arr:", arr);
// arr: [ '吕大', '赵二', '杰尼龟', '皮卡丘', '典小四' ]

12.Array.forEach(function(item, index, arr))

用于调用数组的每个元素,并将元素传递给回调函数。原数组不变。(注意该方法和map的区别,若直接打印Array.forEach,结果为undefined)

item

必需。当前元素

index

可选。当前元素的索引值。

arr

可选。当前元素所属的数组对象。

forEach只遍历,不生成新数组;map返回新数组

const arr = ["吕大", "赵二", "关三", "典小四"];arr.forEach((item, index) => console.log(`第${index + 1}个人是${item}`));
/* 第1个人是吕大第2个人是赵二第3个人是关三第4个人是典小四 */

13.Array.filter(function(currentValue,index,arr), thisValue)

检测数值元素,并返回符合条件所有元素的新数组。原数组不变。

const arr = [2, 4, 6, 8];const newArr = arr.filter((item) => item > 4);console.log("newArr:", newArr);
// newArr: [ 6, 8 ]

14.Array.every(function(currentValue,index,arr), thisValue)

对数组中的每一项进行判断,若都符合则返回true,否则返回false。不改变原数组。类似于并逻辑

const arr1 = [{ level: "公爵", name: "吕大", isShow: false },{ level: "侯爵", name: "赵二", isShow: false },{ level: "伯爵", name: "关三", isShow: true },{ level: "子爵", name: "典小四", isShow: true },];console.log("arr1:",arr1.every((item) => item.isShow));
// arr1: falseconst arr2 = [{ level: "公爵", name: "吕大", isShow: true },{ level: "侯爵", name: "赵二", isShow: true },];console.log("arr2:",arr2.every((item) => item.isShow));
// arr2: true

15.Array.some(function(currentValue,index,arr), thisValue)

对数组中的每一项进行判断,若都不符合则返回false,否则返回true。不改变原数组。类似于或逻辑

const arr1 = [{ level: "公爵", name: "吕大", isShow: false },{ level: "侯爵", name: "赵二", isShow: false },{ level: "伯爵", name: "关三", isShow: true },{ level: "子爵", name: "典小四", isShow: true },];console.log("arr1:",arr1.some((item) => item.isShow));
// arr1: trueconst arr2 = [{ level: "公爵", name: "吕大", isShow: false },{ level: "侯爵", name: "赵二", isShow: false },];console.log("arr2:",arr2.some((item) => item.isShow));
// arr2: false

16.Array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。不改变原数组

 数组累加、累乘

let arr = [1,2,3,4,5]console.log(arr.reduce("result:",(x,y)=>x+y));
//result: 15console.log(arr.reduce("result:",(x,y)=>x*y));
//result: 120

获取最值(最大值)

let arr = [189, 2, 333, 4, 6, 999, 8, 55, 456, 528];let maxValue = arr.reduce((pre, cur) => {return pre > cur ? pre : cur;});console.log("maxValue", maxValue);
// maxValue 999

获取数组元素出现次数

let arr = [1, 2, 5, 8, 9, 5, 2, 3, 4, 6, 1, 8, 22, 5, 9, 4, 3, 5];let numObj = arr.reduce((pre, cur) => {pre[cur] = pre[cur] ? pre[cur] + 1 : 1;return pre;}, {});console.log("numObj", numObj);
/* numObj {'1': 2,'2': 2,'3': 2,'4': 2,'5': 4,'6': 1,'8': 2,'9': 2,'22': 1} */

二维数组转化为一维数组

let arr = [[2, 3, 4],[6, 7, 8],[10, 11, 12],];let newArr = arr.reduce((pre, cur) => {return pre.concat(cur);}, []);console.log("newArr", newArr);/* newArr [2,  3,  4,  6, 7,8, 10, 11, 12] */

多维数组转化为一维数组

let arr = [[0, 1],[1, 2, 3],[4, [1, 23]],];const newArr = function (arr) {return arr.reduce((pre, cur) => pre.concat(Array.isArray(cur) ? newArr(cur) : cur),[]);};console.log(newArr(arr));
/* [0, 1, 1,  2,3, 4, 1, 23] */

数组去重

let arr = [2, 4, 6, 8, 4, 5, 8, 2, 8, 2, 6, 1, 5, 2, 5];let newArr = arr.reduce((pre, cur) => {if (!pre.includes(cur)) {pre.push(cur);}return pre;}, []);console.log("newArr", newArr);
// newArr [ 2, 4, 6, 8, 5, 1 ]

数组对象根据某个键值去重

let arr = [{ name: "xiaoming", age: 11 },{ name: "xxx", age: 12 },{ name: "xiaoming", age: 11 },];let obj = {};
let newArr = arr.reduce((pre, cur) => {if (!obj[cur.name]) {obj[cur.name] = true;pre.push(cur);}return pre;}, []);console.log("newArr", newArr);
// newArr [ { name: 'xiaoming', age: 11 }, { name: 'xxx', age: 12 } ]

17.Array.indexOf(item,start)

检测当前值在数组中第一次出现的位置索引。如果没有搜索到则返回 -1。不改变原数组

const arr1 = ["apple", "orange", "grape"];console.log("arr1:", arr1.indexOf("orange"));
// arr1: 1const arr2 = ["apple", "orange", "grape", "orange", "banana"];
console.log("arr2:", arr2.indexOf("orange", 2));
// arr2: 3

18.Array.includes(searchElement, fromIndex)

判断一个数组是否包含一个指定的值。如果是返回 true,否则false。不改变原数组

const arr = ["apple", "orange", "grape"];console.log("result1:", arr.includes("orange"));
// result1: trueconsole.log("result2:", arr.includes("orange", 2));
// result2: false

19.Array.find(function(currentValue, index, arr),thisValue)

返回通过测试(函数内判断)的数组的第一个元素的值。如果没有符合条件的则返回 undefined。不改变原数组

const arr = [2, 4, 6, 8];console.log("result:",arr.find((item) => item > 4));
// result: 6

20.Array.findIndex(function(currentValue, index, arr),thisValue)

返回传入一个测试条件(函数)符合条件的数组第一个元素位置。如果没有符合条件的元素返回 -1。不改变原数组

const arr = [2, 4, 6, 8];console.log("result:",arr.findIndex((item) => item > 4));
// result: 2

21.Array.isArray(obj)

判断一个对象是否为数组。obj为要判断的对象,必需。如果对象是数组返回 true,否则返回 false。不改变原数组

console.log(Array.isArray([2, 4, 6, 8]));
// trueconsole.log(Array.isArray({ name: "xiaoming" }));
// false

22.Array.join(separator)

用于把数组中的所有元素转换一个字符串。不改变原数组

separator,可选。指定要使用的分隔符。如果省略该参数,则使用逗号作为分隔符。

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const energy = fruits.join(" and ");console.log("energy:", energy);
// energy: Banana and Orange and Apple and Mango

23.Array.of()

将一组值转换为数组,不考虑参数的数量或类型。

console.log(Array.of(1, "a", [3, 6], { name: "xiaoming" }));
// [ 1, 'a', [ 3, 6 ], { name: 'xiaoming' } ]

24.Array.at()

用于接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。不改变原数组。(慎用,语法比较新,注意浏览器版本和node版本,有兼容性问题)

const arr = ["吕大", "赵二", "关三", "典小四"];console.log(arr.at(-1));
// 典小四

25.Array.flat(depth)

按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。简单来说,就是多维数组扁平化的程度

depth, 指定要提取嵌套数组的结构深度,默认值为 1

flat() 方法会移除数组中的空项

const arr1 = [1, 2, [3, 4]];
console.log(arr1.flat());
// [1, 2, 3, 4]const arr2 = [1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat());
// [1, 2, 3, 4, [5, 6]]const arr3 = [1, 2, [3, 4, [5, 6]]];
console.log(arr3.flat(2));
// [1, 2, 3, 4, 5, 6]//使用 Infinity,可展开任意深度的嵌套数组
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
console.log(arr4.flat(Infinity));
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

其他:

还有一些数组方法,比较深冷,应用场景很低,在此不再演示。如:copyWithin(),entries(),from() ,keys() ,lastIndexOf() ,reduceRight(),toString(),valueOf(),flatMap()。感兴趣的话可以学习了解一下。

注意:

原数组改变的方法有:push pop shift unshift reverse sort splice
不改变原数组的方法有:concat map filter join every some indexOf slice forEach...

小技巧Tip:涉及到数组增,删,改的方法都是改变原数组的;涉及到数组查询类的方法是不改变原数组的

更多推荐

JS数组方法合集(含应用场景)

本文发布于:2023-12-06 21:26:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1668974.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   合集   场景   方法   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!