Array的方法

3 阅读2分钟

写一个数组相关的方法总结,方便自己随时看

不是数组的方法,但给数组用

数组去重

const arr= new Set([1,2,33,2,5,3])  --->[1,2,33,5,3]

静态方法

拷贝

Array.form(arrayLike,mapFn)
arrayLike:要拷贝的对象 mapFn:要拷贝对象的逻辑处理 将类数组或迭代对象中浅拷贝一个数组

Array.from("foo") --->["f","o","o"]
Array.from([1,2,3],x=>{x+x}) --->[ 2, 4, 6 ]
//从nodeList 拷贝
const images = document.querySelectorAll("img")
const sources=Array.from(images,image=>imgae.src)
const httpsSources=sources.filter(link=<link.startsWith("https://"))

实例方法 Array.# prototype.---

遍历数组

forEach()

累加

reduce()
对数组进行累加的操作最终返回一个值 reduce(fn(x),initial) initial 累加的初始值

 const totalCont = array1.reduce(sum => sum + item, 0); // 10

删除并追加

splice(start,int,value)
start 删除的起始下标 int 删除的整数量 ,value 可选

填充

fill(value,start,end)
value 要填充的值,start开始下标 end 结束下标

浅拷贝一个数组

slice(start,end)
start浅拷贝的起始下标,end 结束下标 不包含end

排序

toSorted(fn(x))
按元素升序排序
fn((a,b)=>a-b) 从小到大排序

数组反转

reverse()

数组转字符串

toString()

拼接

join("separator")
separator 的方式不写默认,将数组拼接成一个字符串

创建一个新数组

map()
从一个数组中经过一个函数运算创建出一个新的数组

const array1 = [1, 4, 9, 16]; 
//注意 map调用必须是一个数组  这是与from的区别
const map1 = array1.map((x) => x * 2); ---> [ 2 , 8 , 18 , 32 ]

合并数组

concat()

arr1.concat(arr2,arr3,...)

排除

every()
测试一个数组的所有元素是否能通过指定的函数式 全通过返回true ,一个不通过返回false

[12, 5, 8, 130, 44].every(item => item >= 10); // false
[12, 54, 18, 130, 44].every(item => item >= 10); // true

some()
也是排除,数组里只要有一个,就返回true,一个都没有返回false

[12, 5, 8, 130, 44].some(item => item >= 10); // true
[1, 4, 8, 3, 4].some(item => item >= 10); // false  

过滤

filter() 把满足函数式的所有元素返回成一个新的数组

const words = ["spray", "elite", "exuberant", "destruction", "present"];

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

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

查找

find()
在数组中找到满足函数式的第一个元素并返回这个元素

const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);

includes(value,index)
index 起始下标 判断是否包含一个指定的值 返回true/false

indexOf(value,index)

找出第一次出现这个值的下标,不存在返回-1

展平嵌套数组

flat(depth) depth 为嵌套的深度,不写默认1,不知道深度可写正无穷 Infinity

const arr1 = [1, 2, [3, 4, [5, 6]]];
const flattened1 = arr1.flat(2); // [1, 2, 3, 4, 5, 6]
const arr2 = [1, 2, [3, 4, [5, 6, [7]]]];
const flattened2 = arr2.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7]