js中的哪些遍歷

說到遍歷,首先想到的是數組的遍歷,方法不要太多,比如 for, forEach,map,filter,every,some等

   下面來看下,用法 首先 定義一個數組: 

      

    1. for循環,需要知道數組的長度,才能遍歷,

    2. forEach循環,循環數組中每一個元素並採取操作, 沒有返回值, 可以不用知道數組長度

      

    3. map函數,遍歷數組每個元素,並回調操作,需要返回值,返回值組成新的數組,原數組不變

      

    4. filter函數, 過濾通過條件的元素組成一個新數組, 原數組不變

      

    5. some函數,遍歷數組中是否有符合條件的元素,返回Boolean值

      

    6. every函數, 遍歷數組中是否每個元素都符合條件, 返回Boolean值

      

 

當然, 除了遍歷數組之外,還有遍歷對象,常用方法 in

    

     in 不僅可以用來 遍歷對象,還可以用來遍歷數組, 不過 i 對應與數組的 key值

     

介紹完遍歷,下面說一下工作中遇到的情況,後臺傳給我一個對象數組,我需要排序再顯示,看到有介紹用 sort 排序的方法,如下

   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var arr1 = [
    {name: 'te', value: 5},
    {name: 'te', value: 2},
    {name: 'we', value: 3},
    {name: 'ee', value: 1},
    {name: 'ee', value: 4}
];
 
var by = function(type){
    return function(o,p){
        console.log(o,p);
        var a;
        var b;
        if(typeof o === 'object' && typeof p === 'object' && o && p){
            a = o[type];
            b = p[type];
            if(a === b) {
                return 0;
            }
            if(typeof a === typeof b){
            console.log(a, b);
                return a < b ? -1 : 1
            }
            return typeof a < typeof b ? -1 : 1;
        }else {
            throw('字段有誤');
        }
    }
}
console.log(arr1.sort(by('value')));

  顯示如下:

    

 

總結:

  排序應用場景很多 , 所以要弄清楚,明白,方可遊刃有餘。望小夥伴多多提意見!

 

補充:  後面發現, 後臺傳過來的數組中,每個對象按 value 排序, value > 5的按順序排在前面,小於5排在後面

    思考後, 可以在原來的的方法中這樣寫,將數組分成2段,大於等於5和小於5,交換位置即可

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var arr1 = [
    {name: 'te', value: 5},
    {name: 'te', value: 2},
    {name: 'we', value: 3},
    {name: 'ee', value: 1},
    {name: 'ee', value: 4}
];
 
 
var sortObj = function(arr, type , num){
    var by = function(type){
        return function(o,p){
            var a;
            var b;
            if(typeof o === 'object' && typeof p === 'object' && o && p){
                a = o[type];
                b = p[type];
                if(a === b) {
                    return 0;
                }
                if(typeof a === typeof b){
                console.log(a, b);
                    return a < b ? -1 : 1
                }
                return typeof a < typeof b ? -1 : 1;
            }else {
                throw('字段有誤');
            }
        }
    };
 
    var cacheArr = arr.sort(by('value'));
 
    //通過num 把數組分成兩段
    var arrBf = cacheArr.filter(function(item){
        if(item.value < num){
            return item;
        }
    });
    var arrAf = cacheArr.filter(function(item){
        if(item.value >= num){
            return item;
        }
    });
 
    //交換位置 即可得到
    var newArr = arrAf.concat(arrBf);
    return newArr;
};
console.log(sortObj(arr1, 'value' , 3));

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章