02-遍历数组的方法

 1 //ES5 中遍历数据的方法
 2 
 3 // 1.forEach()  遍历
 4 // 需求:遍历数组["张飞","关羽","赵云","马超"]
 5 let arr1 = ["张飞","关羽","赵云","马超"];
 6 arr1.forEach((v,i) => console.log(v))   // "张飞","关羽","赵云","马超"
 7 
 8 
 9 // 2.map()  映射        遍历数组,返回一个经过函数处理过的数组,数组的长度不变;
10 // 需求:遍历数组,求每一项的平方存在于一个数组中
11 let arr2 = [1,2,3,4,5]
12 arr2 = arr2.map(item => item * item )
13 console.log(arr2)   // [ 1, 4, 9, 16, 25 ]
14 
15 
16 // 3.filter()   过滤        过滤出符合条件的值,返回一个新数组
17 //需求:遍历数组,将数组中工资超过5000的值过滤出来 [1000, 5000, 20000, 3000, 10000, 800, 1500]
18 let arr3 = [1000, 5000, 20000, 3000, 10000, 800, 1500]
19 arr3 = arr3.filter( item => item >= 5000)
20 console.log(arr3);      // [ 5000, 20000, 10000 ]
21 
22 
23 // 4.some()    判断         数组中有一个值满足判读条件,就返回true
24 //需求:遍历数组,判断数组是否包含奇数,[2,4,6,8,10,9]
25 let arr4 = [2,4,6,8,10,9]
26 let b1 = arr4.some( item => item %2 === 1)
27 console.log(b1);    // true
28 
29 
30 // 5.every()    判断        数组中全部都满足条件,就返回true
31 //需求:遍历数组,判断数组是否都是偶数,[2,4,6,8,10,9]
32 let arr5 = [2,4,6,8,10,9]
33 let b2 = arr5.every( item => item %2 === 0 )
34 console.log(b2);    // false
35 
36 
37 // 6.find()     过滤        过滤出符合条件的第一个值,否则就返回undefined
38 // 获取第一个大于10的数
39 let arr6 = [5, 12, 8, 130, 44];
40 arr6 = arr6.find( item => item > 10)
41 console.log(arr6);  // 12
42 
43 
44 /// 7.findIndex()      过滤出符合条件的第一个值的索引,否则就返回-1
45 // 获取第一个大于10的下标
46 let arr7 = [5, 12, 8, 130, 44]
47 arr7 = arr7.findIndex( item => {
48     return item > 10
49 })
50 console.log(arr7);  // 1

猜你喜欢

转载自www.cnblogs.com/sikongdada/p/10498733.html