网站首页 > 基础教程 正文
可能有的同学要问了,我们真的需要了解所有这些方法吗?我告诉你,是的,肯定需要了解的。
原因很简单,因为有时当你尝试编写一些逻辑去实现你的目标时,你往往可能使用的不是一个正确的,或者说更好更适合的数组方法去实现的。这样可能导致你的代码看起来更长,可读性更差。
这就是我接下要讲的40个JS数组可用的方法
1. Array.forEach()
实例:
array1.forEach( (item) => { console.log(item)} )
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element));
> "a"
> "b"
> "c"
特点:第一个参数始终是元素
2. Array.map()
实例:
array1.map( (item) => item + item )
const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => x * 2);
console.log(map1);
> Array [2, 8, 18, 32]
特点:返回新数组,不改变原数组
3. Array.filter()
实例:
words.filter( (item) => item.type !== 'fruit' )
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
> Array ["exuberant", "destruction", "present"]
特点:返回数组,包含符合条件的所有元素
4. Array.concat()
实例:
array1.concat(vegetables)
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
> Array ["a", "b", "c", "d", "e", "f"]
特点:创建新数组,不会改变原数组
5. Array.find()
实例:
array1.find((item) => item.color === 'yellow')
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);
> 12
特点:返回首个满足条件的元素
6. Array.findIndex()
实例:
array1.findIndex((item) => item.color === 'yellow')
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
> 3
特点:返回满足条件的元素索引,否则返回-1
7. Array.indexOf()
实例:
beasts.indexOf('apple')
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// Start from index 2
console.log(beasts.indexOf('bison', 2));
console.log(beasts.indexOf('giraffe'));
> 1
> 4
> -1
特点:返回第一个目标元素的索引,否则返回-1,可设置起始查询位置
8. Array.lastIndexOf()
实例:
animals.lastIndexOf('apple')
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
console.log(animals.lastIndexOf('Dodo'));
console.log(animals.lastIndexOf('Tiger'));
> 3
> 1
特点:从数组末尾开始搜索,返回第一个目标元素的索引,否则返回-1
9. Array.some()
实例:
array.some((item) => item === 'apple')
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even));
> true
特点:找到满足条件元素时返回true,否则false
10. Array.every()
实例:
array1.every((item) => item === 'apple')
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
> true
特点:有一个元素不满足就返回false,否则true
11. Array.includes()
实例:
array1.includes('apple')
const array1 = [1, 2, 3];
console.log(array1.includes(2));
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
console.log(pets.includes('at'));
> true
> true
> false
特点:数组包含元素返回true,否则false
12. Array.push()
实例:
animals.push('apple')
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
console.log(animals);
> 4
> Array ["pigs", "goats", "sheep", "cows"]
特点:往数组末尾添加元素
13. Array.unshift()
实例:
array1.unshift('apple')
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
console.log(array1);
> 5
> Array [4, 5, 1, 2, 3]
特点:往数组开头添加元素,返回调用方法的对象的新length属性
14. Array.pop()
实例:
plants.pop('apple')
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
console.log(plants);
plants.pop();
console.log(plants);
> "tomato"
> Array ["broccoli", "cauliflower", "cabbage", "kale"]
> Array ["broccoli", "cauliflower", "cabbage"]
特点:删除数组最后一个元素,如果数组为空,则为 undefined
15. Array.shift()
实例:
array1.shift('apple')
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
console.log(firstElement);
> Array [2, 3]
> 1
特点:删除数组第一个元素
16. Array.toString()
实例:
array1.toString('apple')
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
> "1,2,a,1a"
特点:将数组转成自符串,不改变原数组
17. Array.join()
实例:
elements.join(',')
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
console.log(elements.join(''));
console.log(elements.join('-'));
> "Fire,Air,Water"
> "FireAirWater"
> "Fire-Air-Water"
特点:将数组使用指定符号连接成自符串,如果省略,则数组元素用逗号(“,”)分隔
18. Array.fill()
实例:
array1.fill('apple', 2, 6)
const array1 = [1, 2, 3, 4];
console.log(array1.fill(0, 2, 4));
console.log(array1.fill(5, 1));
console.log(array1.fill(6));
> Array [1, 2, 0, 0]
> Array [1, 5, 5, 5]
> Array [6, 6, 6, 6]
特点:使用指定内容填充数组
19. Array.copyWithin()
实例:
array1.copyWithin(2, 0)
const array1 = ['a', 'b', 'c', 'd', 'e'];
console.log(array1.copyWithin(0, 3, 4));
console.log(array1.copyWithin(1, 3));
> Array ["d", "b", "c", "d", "e"]
> Array ["d", "d", "e", "d", "e"]
特点:从数组的指定位置拷贝元素到数组的另一个指定位置中
20. Array.slice()
实例:
animals.slice(2, 4)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Array ["camel", "duck"]
console.log(animals.slice());
// Array ["ant", "bison", "camel", "duck", "elephant"]
特点:返回现有数组的一部分,原数组不变
21. Array.splice()
实例:
months.splice(1, 0, ‘apple’)
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
// Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
console.log(months);
// Array ["Jan", "Feb", "March", "April", "May"]
特点:
从数组中插入或者替换元素
返回一个数组,包含被删除的元素
如果只删除一个元素,则返回一个元素的数组
如果没有删除任何元素,则返回一个空数组
22. Array.sort()
实例:
months.sort()
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Array [1, 100000, 21, 30, 4]
特点:数组元素排序
23. Array.reverse()
实例:
array1.reverse()
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// Array ["three", "two", "one"]
console.log('array1:', array1);
// Array ["three", "two", "one"]
特点:反转数组
24. Array.from()
实例:
Array.from(numbers)
console.log(Array.from('foo'));
// Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Array [2, 4, 6]
特点:最简单的应用就是克隆一个数组
25. Array.isArray()
实例:
Array.isArray(numbers)
console.log(Array.isArray([1, 3, 5]));
// true
console.log(Array.isArray('[]'));
// false
console.log(Array.isArray(new Array(5)));
// true
console.log(Array.isArray(new Int16Array([15, 33])));
// false
特点:判断是否是一个数组
如果value是Array,则为true,否则为false。如果value是 TypedArray实例,则始终返回false
26. Array.valueOf()
实例:
fruits.valueOf()
const fruits = ["a", "b", "c", "d"];
const myArray = fruits.valueOf();
console.log(myArray);
// Array ["a", "b", "c", "d"]
特点:返回数组本身,而不做任何更改
27. Array.entries()
实例:
array1.entries()
const array1 = ['a', 'b', 'c'];
const iterator = array1.entries();
for (const key of iterator) {
console.log(key[0], key[1]);
}
> 0 "a"
> 1 "b"
> 2 "c"
特点:返回新的数组迭代器对象,该对象包含数组中每个索引的键/值对
28. Array.keys()
实例:
array1.keys()
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key); // 0 1 2
}
特点:得到一个所有键的数组
29. Array.values()
实例:
array1.values()
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
> "a"
> "b"
> "c"
特点:得到一个所有键值的数组
30. Array.reduce()
实例:
array1.reduce()
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
> 10
特点:最终结果是单个值
31. Array.reduceRight()
实例:
arr.reduceRight()
const arr = [2, 3, 4, 5, 6, 7, 8, 9]
const i = arr.reduceRight((pv, cv, ci) => {
console.log("curentValue: " + cv + " previousValue: " + pv)
return 2 * cv;
})
console.log(i);
> "curentValue: 8 previousValue: 9"
> "curentValue: 7 previousValue: 16"
> "curentValue: 6 previousValue: 14"
> "curentValue: 5 previousValue: 12"
> "curentValue: 4 previousValue: 10"
> "curentValue: 3 previousValue: 8"
> "curentValue: 2 previousValue: 6"
> 4
特点:最终结果是单个值
32. Array.flat()
实例:
arr1.flat()
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
> Array [0, 1, 2, 3, 4]
特点:返回一个新数组,其中的子数组元素连接在一起
33. Array.flatMap()
实例:
arr1.flatMap()
const arr1 = [1, 2, 1];
const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));
console.log(result);
> Array [1, 2, 2, 1]
特点:返回一个新数组,其中每个元素都是回调函数的结果,并按深度 1 平展
34. Array.at()
实例:
array1.flatMap()
const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(array1.at(index));
index = -2;
console.log(array1.at(index));
> 8
> 130
特点:数组中与给定索引匹配的元素
35. Array.findLast()
实例:
array1.findLast()
const array1 = [5, 12, 50, 130, 44];
const found = array1.findLast((element) => element > 45);
console.log(found);
> 130
特点:数组中满足所提供测试函数的最后一个(最高索引)元素
36. Array.of()
实例:
array1.of()
console.log(Array.of('foo', 2, 'bar', true));
console.log(Array.of());
> Array ["foo", 2, "bar", true]
> Array []
特点:一个新Array实例
37. Array.fromAsync()
实例:
Array.fromAsync()
const asyncIterable = (async function* () {
for (let i = 0; i < 5; i++) {
await new Promise((resolve) => setTimeout(resolve, 10 * i));
yield i;
}
})();
Array.fromAsync(asyncIterable).then((array) => console.log(array));
> [0, 1, 2, 3, 4]
特点:一个新的`Promise`实例,其履行值是一个新Array实例
38. Array.with()
实例:
arr.with()
const arr = [1, 2, 3, 4, 5];
// 下面2是索引 6是值
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
特点:元素`at`index替换为value的新数组
39. Array.toSorted()
实例:
Array.toSorted()
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']
const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]
特点:元素按升序排序的新数组
40. Array.toLocaleString()
实例:
Array.toSorted()
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);
> "1,a,12/21/1997, 2:12:00 PM"
特点:表示数组元素的字符串
猜你喜欢
- 2024-11-06 javascript夯实基础-3 javascript基础教程9
- 2024-11-06 JavaScript 数组方法 js数组方法some
- 2024-11-06 JAVASCRIPT数组详解(一) js数组菜鸟教程
- 2024-11-06 JavaScript 数组的常用方法 js中数组的方法
- 2024-11-06 JavaScript 数组嵌套对象的排序方法
- 2024-11-06 javascript中的内存管理 js内存条
- 2024-11-06 JS的赋值与深浅拷贝实例 js 深度复制
- 2024-11-06 Javascript 字符串和数组同名的方法有哪些?
- 2024-11-06 使用nginx-http-concat优化网站响应
- 2024-11-06 JavaScript 数据类型——String javascript中数据类型分为哪两大类
- 最近发表
-
- 掌握SpringBoot-2.3的容器探针:实战篇
- kubernetes基础知识之驱逐节点(k8s驱逐节点后恢复)
- Linux环境中制作网络哨兵Sentinel Docker镜像
- k8s之配置CNI网络(k8s 网络配置)
- docker实战之:镜像更新(docker 镜像升级替换)
- 离线在docker镜像方式部署ragflow0.17.2
- Linux日常小技巧Docker打包(docker打包lnmp)
- 使用dockerfile构建docker镜像(docker通过dockerfile构建镜像命令)
- 「云原生」Containerd ctr,crictl 和 nerdctl 命令介绍与实战操作
- Kylin安装Dify(kylin安装部署)
- 标签列表
-
- jsp (69)
- pythonlist (60)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- pythonif (68)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)