// 1. fill 替换/填充数组 // fill(value,start,end) 语法规则 // value: 要填充的值; start:起始索引; end: 结束索引 // tip: 1. 包左不包右 (即不包含结束索引)'; 2. fill()方法会修改原始的数组,并且返回修改后呃数组 const arr = [1, 2, 3, 4, 5, 7] arr.fill(6, 0, 5) console.log(arr); // [6,6,6,6,6,7]
// 2. find 查找元素 // 语法: find() // 该方法会返回第一个满足条件的元素, 如果找不到会返回`undefined` const arr1 = [{ name: "张三" }, { name: "李四" }, { name: "王五" }] const people = arr1.find(el => el.name === "张三") console.log(people, typeof people, people.name); // {name:"张三"} const arrNum = [121, 123, 122, 56, 8, 99, 233, 0] const filterNum = arrNum.find(el => el > 200) console.log(filterNum); // 233
// 3. findIndex() // 该方法会返回满足条件元素所对应的索引,如果找不到就返回返回-1 console.log(arrNum.findIndex(el => el === 10)); // 7
// 4. sort 对数组元素进行排序 tip: 会改变原始数组,并且返回排序之后的数组 const arr3 = [1, 3, 2, 6, 5, 8] const SortArr3 = arr3.sort() console.log(`原数组${arr3}`, `修改之后的数组:${SortArr3}`); //原数组1,2,3,5,6,8 修改之后的数组:1,2,3,5,6,8 // 可以看到这里排序完之后,对原数组也造成了影响 ,那么有没有办法可以不影响原来的数组吗? // es2023 推出了新的API // 5. toSorted() 对数组进行排序 与sort的唯一区别是不会影响原数组 const arr4 = [1, 5, 4, 6] const SortedArr = arr4.toSorted() console.log(`使用toSorted api对数组进行排序之后:${arr4}`); // [1,5,4,6]
// 6. toReversed() 反转数组 与reverse()的区别就是不会对原数组造成影响 const arr5 = [1, 2, 3, 4, 5] const reverArr = arr5.toReversed() console.log(`使用toRevered api对数组进行反转之后,原数组:${arr5},新数组:${reverArr}`);
// 7. with() 替换数组里面的某个值,不会改变原数组 // 语法: with(index,value) // index: 要替换值的索引; value: 要替换的值; const arr6 = [1, 2, 3]; const newArray = arr6.with(1, false); // [1, false, 3] console.log(`使用with api 对数组进行修改之后 , 原数组:${arr6},新数组: ${newArray}`);